sys.exit(1) vs raise SystemExit vs raise

Ben Finney ben+python at benfinney.id.au
Sat Apr 16 00:13:43 EDT 2016


cs at zip.com.au writes:

> My preferred pattern is like this:
>
>  def main(argv):
>    try:
>      ...
>    except Exception as e:
>      logging.exception(e)
>      return 1
>
>  if __name__ == '__main__':
>    sys.exit(main(sys.argv))
>
> Notice that main() is back to being a normal function with normal
> returns.

That's good. A couple of points:

* If you allow ‘main’ to be called with no arguments, and default to the
  actual command-line, then ‘main’ becomes a function you can use as a
  Setuptools entry point.

* If the ‘main’ function encounters no exception, it will return ‘None’
  instead of the correct exit status of 0.

* You can use named constants from ‘os’ for the purpose of specifying
  exit status numbers.

  <URL:https://docs.python.org/3/library/os.html#os._exit>

So::

    def main(argv=None):
        """ Mainline procedure for this program.

            :param argv: Sequence of command-line arguments.
                Default: `sys.argv`.
            :return: Exit status (integer) for this program.

            """
        exit_status = os.EX_OK

        if argv is None:
            argv = sys.argv

        try:
            ...
        except Exception as exc:
            logging.exception(exc)
            exit_status = os.EX_SOFTWARE

        return exit_status

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

-- 
 \      “He that would make his own liberty secure must guard even his |
  `\                             enemy from oppression.” —Thomas Paine |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list