简体   繁体   中英

Python subprocess module: Catch exception from a child process in parent process

How to catch exception from a child process in the parent process. The child process is created using Python's subprocess.Popen() like so:

division_by_zero.py

print(1/0)

parent.py

import subprocess
subprocess.Popen(['python', 'division_by_zero.py'])

The child process raises an exception

ZeroDivisionError: integer division or modulo by zero

. How to catch that in parent process?

I don't think there is a way to directly "catch" that exception. But I have only started researching this myself.

You could use pipes for a similar result, like so:

in parent.py

import subprocess 

process = subprocess.Popen(['python', 'division_by_zero.py'], stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
errorText = stderr.decode()
if 'ZeroDivisionError' in errorText:
    print('Zero divison error encountered while executing subprocess')

in division_by_zero.py

print(0/1)

The trick is that we redirect all error output to a pipeline between our process and the subprocess. Normal output can also be captured in a similar fashion by passing stdout=subprocess.PIPE to .Popen() function.

Inspired by this answer: https://stackoverflow.com/a/35633457/13459588

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