Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it ok to call sys.exit() from within context manager in Python?

For example, I’ve something using the "with" statement, and I do something inside the "with" that can throw an exception, and I want to catch the exception so that I can use sys.exit(0) / sys.exit(1) so the pass / fail result can be picked up by the calling script/shell.

with open("test.txt", "r") as f:
    try:
        do_something_with(f)
    except Exception as e:
        sys.exit(1)
    else:
        sys.exit(0)

In my case, it’s not a file I’m opening but a connection to a server, and I just want to know if the context manager’s __exit__ will get called properly, or if sys.exit() somehow bypasses it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, the context manager’s __exit__ will still be called.

You can test this yourself by creating your own dummy context manager:

import contextlib
import sys


@contextlib.contextmanager
def my_context_manager():
    try:
        print("enter")
        yield
    finally:
        print("exit")


with my_context_manager():
    print("inside")
    sys.exit(1)

Running this script outputs

enter
inside
exit

This should make sense, since sys.exit works by raising SystemExit, which is just a slightly special exception that does not inherit from Exception. You can even catch it if you like:

try:
    sys.exit(1)
except SystemExit:
    print("caught exit")

print("I survived sys.exit!")

outputs

caught exit
I survived sys.exit!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading