繁体   English   中英

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

[英]In Python 2 or 3, how to get both the return code and return string of system call?

我知道我可以这样做来执行一个系统命令,例如make,它会给我一个0表示成功,或者一个非零表示失败。

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

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

import commands
result = commands.getoutput('make')

如何同时获得返回代码和返回字符串结果,我怎么能完成两者,所以我可以

if return_code > 0:
  print(return_string)

谢谢。

使用Python运行东西的规范方法是使用subprocess进程模块,但它有一大堆check_call的函数叫做check_callcheck_output ,这些函数往往会有一些神秘的警告,例如“不要使用stdout = PIPE或stderr = PIPE功能“,所以让我提供更多:

第1步:运行脚本

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

现在该过程在后台运行,您可以参考它。

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

第2步:等待进程完成并获取其输出

stdout, sterr = proc.communicate()
return_code = proc.returncode

communicate可以让你做更多的事情:

  • 将stdin数据传递给进程( input= parameter)
  • 为完成过程提供时间限制,以避免挂起( timeout=参数)

确保捕获并正确处理来自Popen任何异常或进行communicate


如果您不关心旧的Python,那么有一个更简单的方法叫做subprocess.run ,它可以全部:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM