在Python2或3中,如何同时获得系统调用的返回码和返回字符串?

2024-10-04 03:27:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道我可以这样做来获得executea system命令,例如make,它会给我一个0表示成功,或者给一个非0表示失败。在

import os
result = os.system('make')

我也知道我可以这样做,这样我就可以看到命令的返回字符串

^{pr2}$

我怎样才能同时得到返回代码和返回字符串结果,这样我就可以做到了

if return_code > 0:
  print(return_string)

谢谢。在


Tags: 字符串代码import命令stringmakereturnif
2条回答

使用Python运行stuff的规范方法是使用subprocess模块,但是它有很多函数神秘地称为check_call或{},这些函数往往有一些神秘的警告,比如“不要将stdout=PIPE或stderr=PIPE与此函数一起使用”,因此让我再提供一些:

步骤1:运行脚本

proc = subprocess.Popen(["your_command", "parameter1", "paramter2"],
                        stdout=subprocess.PIPE, stderr=subprocess.PIPE)

现在该进程正在后台运行,并且您有了对它的引用。在

编辑:我差点忘了——如果您想稍后检索输出,您必须告诉Python为标准输出创建读取管道。如果不执行此步骤,stdout和stderr将只转到程序的标准输出和标准错误,communicate将不会在步骤2中获取它们。在

步骤2:等待进程完成并获得其输出

^{pr2}$

^{}还允许您执行更多操作:

  • 将stdin数据传递给进程(input=参数)
  • 指定进程完成的时间限制,以避免挂起(timeout=参数)

确保还捕获并正确处理来自^{}或{a1}的任何异常。在


如果您不关心旧的Python,有一种更简单的方法,称为^{}来完成这一切:

completed_process = subprocess.run(
    ['your_command', 'parameter'],
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE)
# this starts the process, waits for it to finish, and gives you...
completed_process.returncode
completed_process.stdout
completed_process.stderr

对于错误检查,您可以调用completed_process.check_returncode(),或者只将check=True作为run的附加参数传递。在

另一种可能更简单的方法是:

import subprocess
try:
 output = subprocess.check_output("make", stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
  print('return code =', e.returncode)
  print(e.output)

相关问题 更多 >