python - x = os.system(..) 的返回值

标签 python linux os.system

<分区>

当我以 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/

相关文章:

Python - 如何在不使用库的情况下连续计算列表的索引?

c++ - 当我对共享库使用 "stripped, with debug_info"命令时, "file"是什么意思?

Python同步运行?一次运行一个可执行文件

python - 如何从 os.system() 获取输出?

python - Ubuntu 18.04 上 Python 的 os.system 和 subprocess.check_output 中莫名其妙的 shell 命令取消转义行为

python - 如何获得完美的音频时序

python - 如何让queue.get尽快返回

python - 如何从 python 中的 RFC 2822 邮件 header 中提取多个电子邮件地址?

c - 微基准测试显示进程切换比线程切换更快;怎么了?

linux - 在本地安装 zlib