gpt4 book ai didi

python - 运行 python 包

转载 作者:IT老高 更新时间:2023-10-28 20:33:29 28 4
gpt4 key购买 nike

在 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

此时我迷路了。为什么是非包?那么代码该如何组织呢?

最佳答案

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

关于python - 运行 python 包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6630822/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com