简体   繁体   中英

Python Pandoc Subprocess Not Printing STDOUT When Exception Occurs

I'm trying to run a process with subprocess and print its entire output if and only if an exception occurs.

Where I was before:

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

This did not work.

Output when subprocess.CalledProcessError occurs:

b'' 

Replacing capture_output with stdout=subprocess.PIPE resulted in the output of everything regardless whether an exception occurred or not, error.output was still empty.

So I experimented:

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())

I also tried subprocess.check_output() which to my information does the same as subprocess.run() with the flags I set in the first code snippet.

What am I missing here? Thanks.

Addendum

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)

This is an MWE with the specific process I want to run ( pandoc )

Output

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

$ ./samplecode.py
Exception:
b''

So the exception gets triggered, but the output object is empty.

It seems that the error message is present in error.stderr and not in error.output. I tried your example (with a ls of non-existent file) :

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)

The output is the following :

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

Hope it helps.

I believe what you're meaning to run is stderr=subprocess.PIPE . This should print the relevant error code to the standard console error output.

Example:

process = subprocess.Popen(['ls', 'myfile.txt'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(output,error) = process.communicate()
if error:
    print error

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM