x的返回值= os.system(..) [英] Return value of x = os.system(..)

查看:108
本文介绍了x的返回值= os.system(..)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我以root身份在Python中键入os.system("whoami")时,它将返回root,但是当我尝试将其分配给变量x = os.system("whoami")时,它将x的值设置为0.为什么? (:

When I type os.system("whoami") in Python, as root, it returns root, but when I try to assign it to a variable x = os.system("whoami") it set's the value of x to 0. Why ? (:

推荐答案

os.system() 返回(编码的)进程退出值. 0表示成功:

在Unix上,返回值是以wait()指定的格式编码的进程的退出状态.请注意,POSIX没有指定C system()函数的返回值的含义,因此Python函数的返回值与系统有关.

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

您看到的输出将被写入stdout,因此您的控制台或终端不会返回到Python调用程序.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

如果您想捕获stdout,请使用 subprocess.check_output() 代替:

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

这篇关于x的返回值= os.system(..)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆