Kees Valkhof
Kees Valkhof

Reputation: 81

python runpy.run_module exit code

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.

Upvotes: 3

Views: 2286

Answers (2)

Tom Weiss
Tom Weiss

Reputation: 1

There's another way to do it that involves creating your own custom exception:

class TerminatedException(Exception):
    """Exception for when a process is terminated."""

    def __init__(self, data: any):
        """Create a new TerminatedException exception."""
        self.data = data

Then raise and catch this exception. This also allows you to pass data back to the calling model.

Upvotes: 0

Kees Valkhof
Kees Valkhof

Reputation: 81

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.

Upvotes: 4

Related Questions