运行python包

时间:2011-07-08 21:40:28

标签: python module package main python-2.6

在OSX上运行Python 2.6.1,将部署到CentOS。想要从命令行调用包:

python [-m] tst

为此,这是目录结构:

$PYTHONPATH/
    tst/
        __init__.py     # empty
        __main__.py     # below
        dep.py          # below

以下是文件:

$ cat tst/__main__.py
from .dep import DepClass

print "Hello there"

$ cat tst/dep.py
class DepClass(object):
    pass

$

然而,python给了我相互矛盾的诊断:

$ python -m tst
/usr/bin/python: tst is a package and cannot be directly executed

好的,所以它被认为是一个包。所以我应该能够将其作为脚本运行?它有__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

此时我迷路了。为什么non-package?那么如何构建代码呢?

1 个答案:

答案 0 :(得分:31)

在Python 2.7中引入了在使用命令行__main__选项时运行包的-m模块的功能。对于2.6,您需要指定要运行的包模块名称; -m test.__main__应该有效。请参阅文档here