python – What is

The Question :

361 people think this question is useful

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

The Question Comments :

The Answer 1

360 people think this answer is useful

Often, a Python program is run by naming a .py file on the command line:

$ python

You can also create a directory or zipfile full of code, and include a Then you can simply name the directory or zipfile on the command line, and it executes the automatically:

$ python my_program_dir
$ python
# 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 file. It can, but it usually doesn’t. When you run a script like python, 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 file.

The Answer 2

110 people think this answer is useful

What is the file for?

When creating a Python module, it is common to make the module execute some functionality (usually contained in a main function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:

if __name__ == '__main__':
    # execute only if run as the entry point into the program

You can get the same semantics for a Python package with This is a linux shell prompt, $, if you don’t have Bash (or another Posix shell) on Windows just create these files at demo/__<init/main> with contents in between the EOFs:

$ mkdir demo
$ cat > demo/ << EOF
print('demo/ executed')
def main():
    print('main executed')
$ cat > demo/ << EOF
print('demo/ executed')
from __init__ import main

(In a Posix/Bash shell, you can do the above without the << EOFs and ending EOFs by entering Ctrl+D, the end-of-file character, at the end of each cat command)

And now:

$ python demo
demo/ executed
demo/ executed
main executed

You can derive this from the documention. The documentation says:

__main__ — Top-level script environment

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == '__main__':
      # execute only if run as a script

For a package, the same effect can be achieved by including a module, the contents of which will be executed when the module is run with -m.


You can also package this into a single file and run it from the command line like this – but note that zipped packages can’t execute sub-packages or submodules as the entry point:

$ python -m zipfile -c demo/*
$ python
demo/ executed
demo/ executed
main() executed

The Answer 3

34 people think this answer is useful is used for python programs in zip files. The file will be executed when the zip file in run. For example, if the zip file was as such:

and the contents of was

import sys
print "hello %s" % sys.argv[1]

Then if we were to run python world we would get hello world out.

So the file run when python is called on a zip file.

The Answer 4

29 people think this answer is useful

You create in yourpackage to make it executable as:

$ python -m yourpackage

The Answer 5

15 people think this answer is useful

If your script is a directory or ZIP file rather than a single python file, will be executed when the “script” is passed as an argument to the python interpreter.

The Answer 6

8 people think this answer is useful

Some of the answers here imply that given a “package” directory (with or without an explicit file), containing a file, there is no difference between running that directory with the -m switch or without.

The big difference is that without the -m switch, the “package” directory is first added to the path (i.e. sys.path), and then the files are run normally, without package semantics.

Whereas with the -m switch, package semantics (including relative imports) are honoured, and the package directory itself is never added to the system path.

This is a very important distinction, both in terms of whether relative imports will work or not, but more importantly in terms of dictating what will be imported in the case of unintended shadowing of system modules.


Consider a directory called PkgTest with the following structure

:~/PkgTest$ tree
├── pkgname
│   ├──
│   ├──
│   └──

where the file has the following contents:

:~/PkgTest$ cat pkgname/
import os
print( "Hello from I am the file", os.path.abspath( __file__ ) )
print( "I am being accessed from", os.path.abspath( os.curdir ) )
from  testmodule import main as firstmain;     firstmain()
from .secondtest import main as secondmain;    secondmain()

(with the other files defined similarly with similar printouts).

If you run this without the -m switch, this is what you’ll get. Note that the relative import fails, but more importantly note that the wrong testmodule has been chosen (i.e. relative to the working directory):

:~/PkgTest$ python3 pkgname
Hello from I am the file ~/PkgTest/pkgname/
I am being accessed from ~/PkgTest
Hello from I am the file ~/PkgTest/pkgname/
I am being accessed from ~/PkgTest
Traceback (most recent call last):
  File "/usr/lib/python3.6/", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/usr/lib/python3.6/", line 85, in _run_code
    exec(code, run_globals)
  File "pkgname/", line 10, in <module>
    from .secondtest import main as secondmain
ImportError: attempted relative import with no known parent package

Whereas with the -m switch, you get what you (hopefully) expected:

:~/PkgTest$ python3 -m pkgname
Hello from I am the file ~/PkgTest/pkgname/
I am being accessed from ~/PkgTest
Hello from I am the file ~/PkgTest/
I am being accessed from ~/PkgTest
Hello from I am the file ~/PkgTest/pkgname/
I am being accessed from ~/PkgTest

Note: In my honest opinion, running without -m should be avoided. In fact I would go further and say that I would create any executable packages in such a way that they would fail unless run via the -m switch.

In other words, I would only import from ‘in-package’ modules explicitly via ‘relative imports’, assuming that all other imports represent system modules. If someone attempts to run your package without the -m switch, the relative import statements will throw an error, instead of silently running the wrong module.


Add a Comment