Python main() functions

Friday 6 June 2003This is over 21 years old. Be careful.

A few weeks ago, Guido van Rossum wrote about Python main() functions in his weblog. There are good ideas in there, but I didn’t agree with them all. In particular, I thought this was odd:

def main(argv=None):
    if argv is None:
        argv = sys.argv
    # etc...

if __name__ == "__main__":
    sys.exit(main())

To me, it is better to keep the sys.exit and the sys.argv in one place:

def main(argv):
    # etc...

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

The weblog has an active comment system, with Guido responding thoughtfully. After I posted my thoughts, he agreed to “compromise” with me!

By the way: one trick I’ve used in main() functions: when converting numeric arguments from strings in argv, use eval(), not int(). That way, you can use any numeric calculations you want in your command line arguments.

Comments

Add a comment:

Ignore this:
Leave this empty:
Name is required. Either email or web are required. Email won't be displayed and I won't spam you. Your web site won't be indexed by search engines.
Don't put anything here:
Leave this empty:
Comment text is Markdown.