What#39;s a good equivalent to subprocess.check_call that returns the contents of stdout?(返回标准输出内容的 subprocess.check_call 有什么好的等价物?)
问题描述
我想要一个与 subprocess.check_call
的接口相匹配的好方法——即,它在失败时抛出 CalledProcessError
,是同步的,&c -- 但不是返回命令的返回码(如果它甚至这样做的话)返回程序的输出,要么只是标准输出,要么是(stdout,stderr)的元组.
I'd like a good method that matches the interface of subprocess.check_call
-- ie, it throws CalledProcessError
when it fails, is synchronous, &c -- but instead of returning the return code of the command (if it even does that) returns the program's output, either only stdout, or a tuple of (stdout, stderr).
有人有这样的方法吗?
推荐答案
Python 2.7+
from subprocess import check_output as qx
Python 2.7
来自 subprocess.py:
import subprocess
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise subprocess.CalledProcessError(retcode, cmd, output=output)
return output
class CalledProcessError(Exception):
def __init__(self, returncode, cmd, output=None):
self.returncode = returncode
self.cmd = cmd
self.output = output
def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (
self.cmd, self.returncode)
# overwrite CalledProcessError due to `output` keyword might be not available
subprocess.CalledProcessError = CalledProcessError
另请参阅将系统命令输出捕获为字符串 另一个可能的 check_output()
实现示例.
See also Capturing system command output as a string for another example of possible check_output()
implementation.
这篇关于返回标准输出内容的 subprocess.check_call 有什么好的等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:返回标准输出内容的 subprocess.check_call 有什么好的等价物?
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01