[英]Python Pandoc Subprocess Not Printing STDOUT When Exception Occurs
我正在尝试使用子进程运行一个进程,并且仅当发生异常时才打印其整个输出。
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仍然为空。
subprocess.run(
command,
stdout=subprocess.PIPE,
)
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''
因此异常被触发,但是输出对象为空。
似乎错误消息存在于error.stderr中,而不存在于error.output中。 我尝试了您的示例(带有ls不存在的文件):
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
希望能帮助到你。
我相信您要运行的意思是stderr=subprocess.PIPE
。 这应该将相关的错误代码打印到标准控制台错误输出中。
例:
process = subprocess.Popen(['ls', 'myfile.txt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output,error) = process.communicate()
if error:
print error
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.