What is the __main__.py
file for, what sort of code should I put into it and when should I have one at all? :)
views:
115answers:
3__main__.py
is used for python programs in zip files. The __main__.py
file will be executed when the zip file in run. For example, if the zip file was as such:
test.zip
__main__.py
and the contents of __main__.py
was
import sys
print "hello %s" % sys.argv[1]
Then if we were to run python test.zip world
we would get hello world
out.
So the __main__.py
file run when python is called on a zip file.
If your script is a directory or ZIP file rather than a single python file, __main__.py
will be executed when the "script" is passed as an argument to the python interpreter.
Often, a Python program is run by naming a .py file on the command line:
$ python my_program.py
You can also create a directory or zipfile full of code, and include a __main__.py
. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py
automatically:
$ python my_program_dir
$ python my_program.zip
You'll have to decide for yourself if your application could benefit from being executed like this.