Is there any advantage to using a main() in python scripts?
tjreedy at udel.edu
Wed Dec 11 22:22:00 CET 2013
On 12/11/2013 5:26 AM, Ben Finney wrote:
> Better design is to make the argument list a parameter to the ‘main’
> function; this allows constructing an argument list specially for
> calling that function, without ‘main’ needing to know the difference.
> You'll also want to catch SystemExit and return that as the ‘main’
> function's return value, to make it easier to use as a function when
> that's needed.
> def main(argv=None):
> if argv is None:
> argv = sys.argv
> exit_code = 0
> command_name = argv
> config = parse_command_args(argv[1:])
> except SystemExit, exc:
> exit_code = exc.code
> return exit_code
> if __name__ == "__main__":
> import sys
> exit_code = main(sys.argv)
> That way, the normal behaviour is to use the ‘sys.argv’ list and to
> raise SystemExit (via ‘sys.exit’) to exit the program. But ‘main’ itself
> can, without any further changes, be called as a function that receives
> the command line as a parameter, and returns the exit code.
In particular, it is easier to write tests when argv is a parameter.
Terry Jan Reedy
More information about the Python-list