Fix Python – What is __main__.py?

Question

Asked By – Monika Sulik

What is the __main__.py file for, what sort of code should I put into it, and when should I have one?

Now we will see solution for issue: What is __main__.py?


Answer

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
# Or, if the program is accessible as a module
$ python -m my_program

You’ll have to decide for yourself whether your application could benefit from being executed like this.


Note that a __main__ module usually doesn’t come from a __main__.py file. It can, but it usually doesn’t. When you run a script like python my_program.py, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn’t necessarily mean you should be looking for a __main__.py file.

This question is answered By – Ned Batchelder

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0