Running a python package [duplicate]

谁都会走 提交于 2019-11-27 20:54:15

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/6630822/running-a-python-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!