运行 python 包

发布于 2024-11-18 22:54:31 字数 1220 浏览 3 评论 0原文

在 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

此时我迷路了。为什么非打包?那么如何构建代码呢?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

熟人话多 2024-11-25 22:54:31

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文