2

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?

nitin_cherian
  • 6,405
  • 21
  • 76
  • 127
  • Possible duplicate of [Python Multiprocessing: Handling Child Errors in Parent](https://stackoverflow.com/questions/19924104/python-multiprocessing-handling-child-errors-in-parent) – EsotericVoid Jul 24 '17 at 09:35
  • Check this answer [How to catch exception output from Python subprocess.check_output()?](https://stackoverflow.com/questions/24849998/how-to-catch-exception-output-from-python-subprocess-check-output) – kchomski Jul 24 '17 at 13:35

1 Answers1

0

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

MickeyDickey
  • 175
  • 1
  • 9