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?
>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!