Is it possible to get the exit code from a module called through runpy.run_module()?
I wish to replace my
exit_code = subprocess.call('py -m mymodule')
with
runpy.run_module('mymodule')
and still get the exit_code
value.
Where mymodule
is a directory containing a python script __main__.py
which just does sys.exit(1)
Testing runpy.run_module('mymodule')
in an interactive shell closes that shell. I could not find any documentation on that behavior. To me it looks like that the difference between using subprocess.call
and runpy.run_module
is running it as a program or function. If that is the case then the behavior is explained and it is unlikely that I can use runpy.run_module
if I need the exit code.
Can anyone confirm this, possibly with a link to some documentation where I could have found it.
This morning it hit me, so I tested a solution and it worked:
import runpy
try:
runpy.run_module('mymodule')
except SystemExit as exeption:
exitcode = exeption.code
else:
exitcode = 0
The catch is that you have to handle every exception thrown in the module. I am only handling the SystemExit
exception in my example, as it is the only exception that I am interested in.