sys.exit(1) vs raise SystemExit vs raise

Ben Finney ben+python at benfinney.id.au
Tue Apr 12 18:14:40 EDT 2016


Ganesh Pal <ganesh1pal at gmail.com> writes:

> I m on python 2.7 and Linux ,  I have a simple code  need suggestion if  I
>  I could replace sys.exit(1) with raise  SystemExit .

No, but you can replace::

    sys.exit(1)

with::

    raise SystemExit(1)

As you know from reading the ‘sys.exit’ documentation
<URL:https://docs.python.org/3/library/sys.html#sys.exit>, ‘sys.exit’ is
implemented by performing ‘raise SystemExit(exit_status)’. So those do
virtually the same thing.

> ==Actual code==
>
> def main():
>     try:
>         create_logdir()
>         create_dataset()
>         unittest.main()
>     except Exception as e:
>         logging.exception(e)
>         sys.exit(EXIT_STATUS_ERROR)
>
> if __name__ == '__main__':
>     main()

This is good practice, putting the mainline code into a ‘main’ function,
and keeping the ‘if __name__ == '__main__'’ block small and obvious.

What I prefer to do is to make the ‘main’ function accept the
command-line arguments, and return the exit status for the program::

    def main(argv):
        exit_status = EXIT_STATUS_SUCCESS
        try:
            parse_command_line(argv)
            setup_program()
            run_program()
        except SystemExit as exc:
            exit_status = exc.code
        except Exception as exc:
            logging.exception(exc)
            exit_status = EXIT_STATUS_ERROR

        return exit_status

    if __name__ == '__main__':
        exit_status = main(sys.argv)
        sys.exit(exit_status)

That way, the ‘main’ function is testable like any other function:
specify the command line arguments, and receive the exit status. But the
rest of the code doesn't need to know that's happening.

-- 
 \              “Programs must be written for people to read, and only |
  `\        incidentally for machines to execute.” —Abelson & Sussman, |
_o__)              _Structure and Interpretation of Computer Programs_ |
Ben Finney




More information about the Python-list mailing list