发生异常时,Python Pandoc子进程不打印STDOUT

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

我正在尝试使用子进程运行进程并且当且仅当发生异常时才打印其整个输出。

我以前在哪里:

try:
    proc = subprocess.run(
        command,
        capture_output=True,
        check=True,
        text=True,
    )
except subprocess.CalledProcessError as error:
    print(error.output)

这没用。

发生subprocess.CalledProcessError时的输出:

b'' 

用stdout = subprocess.PIPE替换capture_output会导致所有内容的输出,无论是否发生异常,error.output仍为空。

所以我试验了:

This prints everything I would see if I executed the command in the command-line.

subprocess.run(
    command,
    stdout=subprocess.PIPE,
)

This prints out nothing.

proc = subprocess.run(
    command,
    capture_output=True,
)
print(proc.stdout.decode())

我也试过subprocess.check_output(),我的信息和subprocess.run()一样,我在第一个代码片段中设置了标志。

我在这里错过了什么?谢谢。

附录

import subprocess

command = ['pandoc', 'file']

try:
    proc = subprocess.run(
        command,
        capture_output=True,
        check=True,
    )
except subprocess.CalledProcessError as error:
    print('Exception:')
    print(error.output)

这是一个具有我想要运行的特定过程的MWE(pandoc

产量

$ pandoc file
pandoc: file: openBinaryFile: does not exist (No such file or directory)

$ ./samplecode.py
Exception:
b''

因此异常被触发,但输出对象为空。

python exception subprocess pandoc
2个回答
1
投票

似乎错误消息存在于error.stderr中而不是error.output中。我尝试了你的例子(有一个不存在的文件):

import subprocess

command = ['ls', 'file']

try:
    proc = subprocess.run(
        command,
        check=True,
        capture_output=True,
        text=True
    )
except subprocess.CalledProcessError as error:
    print('Exception:')
    print('output : ' + error.output)
    print('stderr : ' + error.stderr)

输出如下:

Exception:
output : 
stderr : ls: file: No such file or directory

希望能帮助到你。


0
投票

我相信你的意思是stderr=subprocess.PIPE。这应该将相关的错误代码打印到标准控制台错误输出。

例:

process = subprocess.Popen(['ls', 'myfile.txt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output,error) = process.communicate()
if error:
    print error
© www.soinside.com 2019 - 2024. All rights reserved.