Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python program start

Tags:

Should I start a Python program with:

if__name__ == '__main__': some code... 

And if so, why? I saw it many times but don't have a clue about it.

like image 809
Kirill Titov Avatar asked Nov 13 '08 15:11

Kirill Titov


2 Answers

If your program is usable as a library but you also have a main program (e.g. to test the library), that construct lets others import the file as a library and not run your main program. If your program is named foo.py and you do "import foo" from another python file, __name__ evaluates to 'foo', but if you run "python foo.py" from the command line, __name__ evaluates to '__main__'.

Note that you do need to insert a space between if and _, and indent the main program:

if __name__ == '__main__':     main program here 
like image 108
Jouni K. Seppänen Avatar answered Oct 12 '22 01:10

Jouni K. Seppänen


A better pattern is this:

def main():    ...  if __name__ == '__main__':    main() 

This allows your code to be invoked by someone who imported it, while also making programs such as pychecker and pylint work.

like image 45
Charles Duffy Avatar answered Oct 12 '22 00:10

Charles Duffy