我想从os.system("nslookup google.com")
得到输出,但是在打印时总是得到0
。为什么是这样的,我该如何解决这个问题? (Python 3中,苹果机)如何获得os.system()的输出?
(我看着How to store the return value of os.system that it has printed to stdout in python? - 但是我不明白吧〜我是新来的Python)
我想从os.system("nslookup google.com")
得到输出,但是在打印时总是得到0
。为什么是这样的,我该如何解决这个问题? (Python 3中,苹果机)如何获得os.system()的输出?
(我看着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']))
如果返回码是不为零,将提出一个CalledProcessError
例外:
try:
print(subprocess.check_output(['nslookup', 'google.com']))
except subprocess.CalledProcessError as err:
print(err)
os.system只返回命令的退出代码。这里0
意味着成功。任何其他数字代表操作系统相关的错误。输出到这个过程的标准输出。 subprocess打算取代os.system
。
subprocess.check_output是围绕subprocess.Popen一个便利的包装,可以简化您的使用情况。
它可以工作。但是,你能解释为什么os.system(command)不打印输出吗? (我是Python新手) – Kamdroid
的可能的复制[如何存储使用os.system的返回值,它具有打印到标准输出的蟒蛇?](http://stackoverflow.com/questions/6746126/how-to-store-the-return- os-system-that-has-print-to-stdout-py-py) – Mel