运行一个Python包

33 投票
1 回答
80395 浏览
提问于 2025-04-16 21:08

我在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 个回答

43

在Python 2.7中,增加了一个功能,可以通过命令行的 -m 选项来运行一个包的 __main__ 模块。而在Python 2.6中,你需要明确指定要运行的包模块名称;比如可以使用 -m test.__main__。想了解更多,可以查看文档 这里

撰写回答