Python 在subprocess.check_调用中捕获stderr而不使用subprocess.PIPE
我想做以下几点:Python 在subprocess.check_调用中捕获stderr而不使用subprocess.PIPE,python,subprocess,stderr,Python,Subprocess,Stderr,我想做以下几点: 使用subprocess从Python向外剥离到另一个可执行文件。检查\u call 捕获子进程的stderr(如果有) 将stderr输出添加到父进程的CalledProcessError异常输出 理论上这很简单。check\u调用函数签名包含一个用于stderr的kwarg: subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False) file_handle = o
- 使用
subprocess从Python向外剥离到另一个可执行文件。检查\u call
- 捕获子进程的stderr(如果有)
- 将stderr输出添加到父进程的CalledProcessError异常输出
check\u调用
函数签名包含一个用于stderr
的kwarg:
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
file_handle = open('some_file', 'w')
subprocess.check_call(args, *, stdin=None, stdout=file_handle, stderr=file_handle, shell=False)
但是,在其正下方包含以下警告:
注意:不要将stdout=PIPE
或stderr=PIPE
与此功能一起使用。由于当前进程中没有读取管道,如果子进程生成足够的输出到管道以填充OS管道缓冲区,则子进程可能会阻塞
问题是,我能找到的从子进程获取stderr的几乎每个示例都提到使用subprocess.PIPE
捕获该输出
如果不使用
子进程.PIPE
,如何从子进程捕获stderr?stdout
和stderr
可以分配给几乎任何可以接收数据的对象,如文件句柄。您甚至可以提供一个打开的文件句柄,用于写入stdout
和stderr
:
subprocess.check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False)
file_handle = open('some_file', 'w')
subprocess.check_call(args, *, stdin=None, stdout=file_handle, stderr=file_handle, shell=False)
现在,输出的每一行都指向同一个文件,或者每个行都有不同的文件
stdin
读起来也像一个文件句柄,使用next()
读取每一行,作为除了初始args
之外要发送的输入命令
这是一个非常强大的函数。请改用subprocess.Popen。是否有办法将stdout/err捕获到变量中,以便我记录它?