I've seen the following code in a couple Python projects, in __main__.py
. Could someone explain the purpose? Of course it puts the directory containing __main__.py
at the head of sys.path
, but why? And why the tests (__package__ is None and not hasattr(sys, 'frozen')
? Also, in the sys.path.insert
, why is os.path.dirname
called twice?
import sys
if __package__ is None and not hasattr(sys, 'frozen'):
# direct call of __main__.py
import os.path
path = os.path.realpath(os.path.abspath(__file__))
sys.path.insert(0, os.path.dirname(os.path.dirname(path)))
The test for __package__
lets the code run when package/__main__.py
has been run with a command like python __main__.py
or python package/
(naming the file directly or naming the package folder's path), not the more normal way of running the main module of a package python -m package
. The other check (for sys.frozen
) tests if the package has been packed up with something like py2exe
into a single file, rather than being in a normal file system.
What the code does is put the parent folder of the package into sys.path
. That is, if __main__.py
is located at /some/path/to/package/__main__.py
, the code will put /some/path/to
in sys.path
. Each call to dirname
strips off one item off the right side of the path ("/some/path/to/package/__main__.py"
=> "/some/path/to/package"
=> "/some/path/to"
).