如何从 os.system() 获取输出? [英] How to get the output from os.system()?

查看:211
本文介绍了如何从 os.system() 获取输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to get output from os.system("nslookup google.com") but instead I always get 0, when printing it. Why is this, and how can I fix this? (Python 3, Mac)

(我看了如何在python中存储它打印到stdout的os.system的返回值?-但我不明白~我是python新手)>

(I looked at How to store the return value of os.system that it has printed to stdout in python? - But I didn't understand it ~ I'm new to python)

推荐答案

使用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.

这篇关于如何从 os.system() 获取输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆