[英]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.