python calling python

Alex Martelli alex at magenta.com
Tue Aug 22 17:03:27 EDT 2000


"Larry Whitley" <ldw at us.ibm.com> wrote in message
news:8nuis2$13os$1 at news.rchland.ibm.com...
    [snip]
> def main()
>     parses sys.argv to get arguments
>
> main() # to get main called
>
> # end of file ---------------------------
>
> Anything else in the above considered harmful in Python?

Just change the very last line to the already-suggested

if __name__=='__main__':
    main()

so that main() will only be called 'automatically' when the script
is passed as the argument to the Python interpreter, and not
every time you import it as a module.  When you do import it
as a module and _want_ to run its main, it's easy to do it
explicitly.

Do keep as 'free code' whatever DOES need to be run every
time the module is imported, of course ('initialization' stuff).


A fine touch might include:

def main(args=sys.argv):
    # whatever

so you can call it more easily from other Python functions (by
passing the arg-list directly); or, code a separate argument
parser function for even finer/easier access from the outside
(e.g. if your args are of the form:
    0 or more --keyword=value
    then 0 or more non-keyword arguments,
you can parse those off sys.argv by default but accept them
directly in your main function -- easier to call from Python...).


Alex






More information about the Python-list mailing list