Running a python package
64,703
The feature to run the __main__
module of a package when using the command line -m
option was introduced in Python 2.7. For 2.6 you need to specify the package module name to run; -m test.__main__
should work. See the documentation here.
Author by
Vlad Didenko
Updated on July 09, 2020Comments
-
Vlad Didenko almost 4 years
Running Python 2.6.1 on OSX, will deploy to CentOS. Would like to have a package to be invoked from a command line like this:
python [-m] tst
For that, here is the directory structure made:
$PYTHONPATH/ tst/ __init__.py # empty __main__.py # below dep.py # below
The following is in the files:
$ cat tst/__main__.py from .dep import DepClass print "Hello there" $ cat tst/dep.py class DepClass(object): pass $
However, python gives me conflicting diagnostic:
$ python -m tst /usr/bin/python: tst is a package and cannot be directly executed
OK, so it is recognized as a package. So I should be able to run it as a script? It has
__main__
...$ python tst Traceback (most recent call last): File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/runpy.py", line 121, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/runpy.py", line 34, in _run_code exec code in run_globals File "/Users/vdidenko/Code/emi/tst/__main__.py", line 1, in <module> from .dep import DepClass ValueError: Attempted relative import in non-package
At this point I am lost. Why
non-package
? And how to structure the code then? -
Vlad Didenko almost 13 yearsGreat, thank you! The docs in 2.6x were kinda vague and confusing between different versions did not help.
-
Nathan Basanese over 8 years// , This is also a problem with statements like
python -m pip install argparse
and the like.