Skip to content
sys.exit(1) versus SystemExit(1)

sys.exit(1) versus SystemExit(1)

March 26, 2009

I used to write Python scripts and have the option parsing go something like this…

if __name__ == "__main__":
    import sys, getopt

    opts, args = getopt.getopt(sys.argv[1:], 'h', ['help'])

    for opt, val in opts:
        if opt in ('-h', '--help'):
            usage(sys.argv)
            sys.exit(1)  # Exit to shell with non-zero result

And then I finally started writing tests for my code, at which point I decided I need to raise SystemExit(1) rather than sys.exit(1) because I imagined Python’s unittest module would get bypassed whenever my code called sys.exit(1).

Except of course I was wrong. sys.exit throws SystemExit in turn, so it comes to the same thing from the point of view of unittest. Failing to read documentation is a very bad habit.

But I prefer throwing the exception myself. You don’t have to import sys if you don’t need it, and it feels prettier (if I had more Python experience I might say more Python-ic).

I used to smoke, drink and dance the hoochie-coo too.

Last updated on