Is there any advantage to using a main() in python scripts?

Ben Finney ben+python at benfinney.id.au
Wed Dec 11 11:26:35 CET 2013


JL <lightaiyee at gmail.com> writes:

> Python scripts can run without a main(). What is the advantage to
> using a main()?

Modular code – that is, implementing the program functionality in small,
well-defined units with narrow, strictly-defined interfaces – is good
design.

Practical benefits include being able to easily use the code as part of
a larger program, and being able to easily unit-test all the program's
code.

> Is it necessary to use a main() when the script uses command line
> arguments? (See script below)
>
> #!/usr/bin/python
>
> import sys
>
> def main():
>     # print command line arguments
>     for arg in sys.argv[1:]:
>         print arg
>
> if __name__ == "__main__":
>     main()

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.

-- 
 \       “Faith, n. Belief without evidence in what is told by one who |
  `\   speaks without knowledge, of things without parallel.” —Ambrose |
_o__)                           Bierce, _The Devil's Dictionary_, 1906 |
Ben Finney




More information about the Python-list mailing list