subprocess.CalledProcessError.stderr in None 尽管被调用程序输出错误消息

问题描述 投票:0回答:1

我试图捕获由

subprocess.check_call
调用的程序的错误消息,但错误对象中的
stderr
始终是
None

这是一个简短的脚本,显示了这一点:

import subprocess
import sys

if '--fail' in sys.argv:  # the script calls itself with this option, for the test
    print('this is the error message', file=sys.stderr)
    sys.exit(1)

try:
    subprocess.check_call([sys.executable, sys.argv[0], '--fail'],
                          stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
    print('Not failed?')  # this neither happens nor is expected
except subprocess.CalledProcessError as err:
    if err.stderr:
        print(err.stderr.decode())  # this is what I expect
    else:
        print('<No error message>')  # this is what happens

我有Python 3.10.12。

python subprocess
1个回答
0
投票

您根本没有从管道缓冲区进行通信,因此内容仍然缓冲在管道中。

check_call
的文档有这样的通知:

注意: 此功能请勿使用

stdout=PIPE
stderr=PIPE

而不是这个:

subprocess.check_call([sys.executable, sys.argv[0], '--fail'],
                      stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)

使用run的更高级别API:

subprocess.run([sys.executable, sys.argv[0], '--fail'],
               capture_output=True, check=True)
© www.soinside.com 2019 - 2024. All rights reserved.