how to stop / terminate / exit a python script Jan

I know this could be trivial to some of you, but it wasn't obvious to me which is why I'm posting. From time to time you might want to hard exit out of your python script. For me this came about when I was writing some system deploy and maintenance scripts. Just returning out of a function wasn't good enough because the rest of the script would keep on trucking. I needed to stop all execution of the script right there before it continued on and did irreversible damage to the system.

This can be done through the sys module.

import sys

It's good to note that all this does is throws a SystemExit exception which can be caught like any other exception.

Alternatively you can use the os._exit() function which terminates at the C level and does not let the interpreter perform any of the normal tear-down procedures. It is not recommended to use os._exit() as sys.exit() should suffice for the vast majority of cases and is the recommended method.

Bookmark and Share
blog comments powered by Disqus