【问题标题】:How to get the output from os.system()? [duplicate]如何从 os.system() 获取输出? [复制]
【发布时间】:2021-09-19 04:58:17
【问题描述】:

我想从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新手)

【问题讨论】:

  • Python 的 os.system("ls") 仅返回 ls 的 exit_code,这是来自操作系统的进程的 unix 整数状态。这里的 0 表示“无错误”。 os.system 的 stdout 和 stderr 都通过管道传输到 python 程序的 stdout 和 stderr 中。因此,您要么手动重新实现此标准输出重定向,要么使用不同的 python 函数自动为您工作,其中一个例子是 subprocess

标签: python python-3.x subprocess os.system


【解决方案1】:

使用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_outputsubprocess.Popen 的便捷包装器,可简化您的用例。

【讨论】:

  • 它有效。但是你能解释一下为什么 os.system(command) 不打印输出吗? (我是 Python 新手)
  • os.system(command) 将命令的输出打印到控制台,但它没有捕获它!例如,files = os.system("ls") 不会将结果存储在文件中。
  • 使用subprocess 而不是os.system
  • 我不断收到带有子进程的FileNotFoundError: [Errno 2] No such file or directory:
  • 尝试shell=True 作为参数。
猜你喜欢
  • 1970-01-01
  • 2013-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 2013-10-14
相关资源
最近更新 更多