开发者

Running a python package [duplicate]

This question already has answers here: Execute an installed Python package as a script? (4 answers) Closed 7 years ago.

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 scrip开发者_如何学Ct? 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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜