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 有什么好的等价物?
				
        
 
            
        基础教程推荐
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - 包装空间模型 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				