且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-15 09:07:04

使用subprocess:

import subprocess
print(subprocess.check_output(['nslookup', 'google.com']))

如果返回码不为零,它将引发一个 CalledProcessError 异常:

If the return code is not zero it will raise a CalledProcessError exception:

try:
    print(subprocess.check_output(['nslookup', 'google.com']))
except subprocess.CalledProcessError as err:
    print(err)

os.system返回命令的退出代码.这里 0 表示成功.任何其他数字代表与操作系统相关的错误.输出到此过程的标准输出.subprocess 打算替换 os.system.

os.system only returns the exit code of the command. Here 0 means success. Any other number stands for an operating-system-dependent error. The output goes to stdout of this process. subprocess intends to replace os.system.

subprocess.check_output 是对 subprocess.Popen 可简化您的用例.

subprocess.check_output is a convenience wrapper around subprocess.Popen that simplifies your use case.