gpt4 book ai didi

python - 返回 stdout 内容的 subprocess.check_call 的等效项是什么?

转载 作者:太空狗 更新时间:2023-10-29 17:40:34 28 4
gpt4 key购买 nike

我想要一个与 subprocess.check_call 接口(interface)匹配的好方法——即,它在失败时抛出 CalledProcessError,是同步的,&c——但是而不是返回命令的返回代码(如果它甚至这样做)返回程序的输出,或者只是 stdout,或者是 (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

另见 Capturing system command output as a string另一个可能的 check_output() 实现示例。

关于python - 返回 stdout 内容的 subprocess.check_call 的等效项是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2924310/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com