sys module - argv, but no argc ??

François Pinard pinard at
Mon Aug 5 14:38:08 CEST 2002

[Greg Ewing]

> I remember the time I wrote a Python program which essentially did

>    import sys, os
>    for f in sys.argv:
>      os.unlink(f)

> and was amused to find that, the first time it was run, it worked
> perfectly and then deleted itself. :-)

Amusing, and instructive! :-)

I had to sit and think about many ways and avenues before choosing a style
for how to handle arguments in a Python program.  I settled for this idiom:

import sys

def main(*arguments):

if __name__ == '__main__'

(the last line was "apply(main, tuple(sys.argv[1:]))" in older times).

One advantage is that `main' does not see the program name as an argument
by default, while the program name can be explicitly accessed through
"sys.argv[0]" for the unusual cases it is really needed.

Another benefit is that the module may be imported interactively, and
interactively called with "main('ARG1', 'ARG2', 'ARG3' ...)"  in a way
which is rather natural.

A final virtue is that the module may be imported from another one, and
its main method called like interactively above, effectively turning one
stand-alone program into an importable function within another, and so,
by not using `os.system' or `os.popen', avoiding spurious Python reloads.
There are other ways to this virtue, of course, but the above choosen
idiom makes it more consistent, especially as we are systematic about it.

François Pinard

More information about the Python-list mailing list