简体   繁体   中英

Python subprocess exception handling

I have a program written in C++ and all it does is divide 1/0 to produce an exception.

I run the .exe of this program via Python's subprocess library. My goal is to capture and log the exception that C++ program makes, within Python.

p = subprocess.Popen(['C:\\Users\\name\\Desktop\\Win32Project1.exe'])

When this line of code executes p is a non zero value meaning an error has occured. I'm running windows 7 and using Python 3.4.1

I'm quite sure you can't track exceptions from a different process. You should try-catch the exception within the C++ program and pass it by one of the many inter-process communication means.

HTH, Cabbi

try this

cmd = ['C:\\Users\\name\\Desktop\\Win32Project1.exe']
out, err = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
print out  # this prints the output of the execution
print err  # this prints if any error is returned

I don't have windows, so this is not tested, but might help you, for more info have a look here

You can also pass other parameters to subprocess.Popen that specify where stdin and stderr go.

Then you can say something like:

p = subprocess.Popen('C:\\Users\\name\\Desktop\\Win32Project1.exe', stdout=PIPE, stderr=PIPE)
(stdout_data, stderr_data) = p.communicate()

rc = p.returncode

# assume 0 return code means o.k.
if rc:
  parse_error(stderr_data)
  # end if

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