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 try: command_name = argv[0] config = parse_command_args(argv[1:]) do_whatever_this_program_does(config) except SystemExit, exc: exit_code = exc.code return exit_code if __name__ == "__main__": import sys exit_code = main(sys.argv) sys.exit(exit_code) 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 -- https://mail.python.org/mailman/listinfo/python-list
