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

How to get the output from os.system()?

我想从 os.system("nslookup google.com") 获得输出,但在打印时我总是得到 0。为什么会这样,我该如何解决? (Python 3, Mac)

(看了How to store the return value of os.system that it has printed to stdout in python? - 但是没看懂~我是新手python)

使用subprocess:

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

如果 return 代码不为零,它将引发 CalledProcessError 异常:

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

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 打算取代 os.system.

subprocess.check_output is a convenience wrapper around subprocess.Popen 可简化您的用例。