简体   繁体   中英

How to know what the error is when I use subprocess.run() in python with exception?

I am converting bash code to python.

I use mkdir of bash through subprocess.run() in python.

In the following example, subprocess.run() raise an exception.

However I could not check what the error is because I could not get an resultant object returned by subprocess.run().

Are there any smart ways to know what the error was? Or should not I use 'try exception' here?

import sys
import subprocess

directory = '/tmp/test_dir'
options = ''

try:

    result=subprocess.run(['mkdir', options, directory], check=True)

except subprocess.CalledProcessError as ex:

    print("In this example, subprocess.run() above raise an exception CalledProcessError.")
    # print("I would like to check result.returncode = {0}. But it failed because object 'result' is not defined.".format(result.returncode))

except Exception as ex:

    sys.stderr.write("This must not happen.")
    sys.exit(1)   

Thank you very much.

you can always do

import subprocess

# make the subprocess
pr = subprocess.Popen(['your', 'command', 'here'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# blocks until process finishes
out, err = pr.communicate() 

# check the return code
if pr.returncode != 0:
    sys.stderr.write("oh no")

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