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

rusi rustompmody at gmail.com
Wed Dec 11 09:24:26 EST 2013


On Wednesday, December 11, 2013 7:47:34 PM UTC+5:30, Roy Smith wrote:
>  JL  wrote:

> > Python scripts can run without a main(). What is the advantage to using a 
> > main()? 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()

> No, it's not necessary, but it's a good idea.

> For one thing, it lets you import your script without actually running 
> it.  We recently tracked down a long-standing bug where some maintenance 
> script we had started out with:

> import os
> os.environ['DJANGO_SETTINGS_MODULE'] = 'whatever'

> somebody imported that script in another part of the system because 
> there was some convenient definition that he wanted to reuse.  
> Unfortunately, the act of importing the script changed the environment!

> The fix was to move the setting of the environment variable to inside 
> the main() routine.  If you always follow the rule that you always put 
> all your executable code inside main(), you'll never run into problems 
> like that.

I guess these are important but somewhat advanced considerations.

For a beginner, its important to get that there is a bit of a pun here:
The function habitually called 'main' may be called that or anything else
It can have or not have an argument as Ben pointed out -- maybe more than 
one also.

The module name __main__ is however sacrosanct and hardwired into python.
The habit of connecting the one with the other is partly conventional and
partly unavoidable



More information about the Python-list mailing list