Python 使用BytesIO作为subprocess.run的stdout/stderr目标

Python 使用BytesIO作为subprocess.run的stdout/stderr目标,python,subprocess,Python,Subprocess,我想运行一个子流程,并将stdout和stderr重定向到不同的目标。subprocess.run方法既可以在内存中捕获输出(参数为capture=True),也可以通过向参数stdout和stderr提供类似文件的值来重定向到文件中。我需要将stdout直接重定向到一个文件中,但希望捕获stderr,以便将错误提供给日志系统。我认为BytesIO非常适合作为类似文件的目标进行捕获,然后从中处理内容。但是,当我运行此代码时: temp\u file\u like=BytesIO(b'') sub

我想运行一个子流程,并将stdout和stderr重定向到不同的目标。
subprocess.run
方法既可以在内存中捕获输出(参数为
capture=True
),也可以通过向参数
stdout
stderr
提供类似文件的值来重定向到文件中。我需要将
stdout
直接重定向到一个文件中,但希望捕获
stderr
,以便将错误提供给日志系统。我认为
BytesIO
非常适合作为类似文件的目标进行捕获,然后从中处理内容。但是,当我运行此代码时:

temp\u file\u like=BytesIO(b'')
subprocess.run(
参数,check=True,shell=False,
stdout=target\u file\u handle,stderr=temp\u file\u like
)
对于str(temp_file_like.getvalue()).split(“\n”)中的行:
记录器。警告(线路)
(代码简化)

我得到一个错误:

File "C:\path\to\script.py", line 143, in run_with_redirect
    stdout=target_file_handle, stderr=temp_file_like
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 488, in run
    with Popen(*popenargs, **kwargs) as process:
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 753, in __init__
    errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "C:\Users\username\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 1106, in _get_handles
    errwrite = msvcrt.get_osfhandle(stderr.fileno())
io.UnsupportedOperation: fileno

在我看来,虽然
subprocess.run
应该接受文件句柄,但
BytesIO
实例并不像文件那样被接受为目标。是否有一种方法可以在将另一个流重定向到文件中时只捕获其中的一个流,而不必使用磁盘上的临时文件?

您可能应该使用subprocess.PIPE作为标准输出,同时让标准输出指向临时文件句柄,然后通过proc.stdout.read()捕获标准输出:


注意:这是另一种方式,因为我正在为
stdout
使用正确的文件句柄,现在使用
PIPE
捕获
stderr
,但这个答案解决了我的问题。非常感谢。
proc = subprocess.Popen(
    arguments,
    check=True,
    shell=False,
    stdout=subprocess.PIPE,
    stderr=temp_file_like
)
output = proc.stdout.read()