<分区>
当我以 root 身份在 Python 中键入 os.system("whoami")
时,它返回 root
,但是当我尝试将其分配给变量时 x = os.system("whoami")
它将 x 的值设置为 0。为什么? (:
<分区>
当我以 root 身份在 Python 中键入 os.system("whoami")
时,它返回 root
,但是当我尝试将其分配给变量时 x = os.system("whoami")
它将 x 的值设置为 0。为什么? (:
最佳答案
os.system()
返回(编码的)进程退出值。 0
表示成功:
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 调用者。
如果你想捕获stdout
,使用subprocess.check_output()
相反:
x = subprocess.check_output(['whoami'])
关于python - x = os.system(..) 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26005583/