运行 python 包 [英] Running a python package
问题描述
在 OSX 上运行 Python 2.6.1,将部署到 CentOS.想要从这样的命令行调用一个包:
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
文件中的内容如下:
$ cat tst/__main__.py
from .dep import DepClass
print "Hello there"
$ cat tst/dep.py
class DepClass(object):
pass
$
但是,python 给了我冲突的诊断:
However, python gives me conflicting diagnostic:
$ python -m tst
/usr/bin/python: tst is a package and cannot be directly executed
好的,所以它被识别为一个包.所以我应该能够将它作为脚本运行?它有 __main__
...
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?
推荐答案
使用命令行 -m
选项时运行包的 __main__
模块的功能是在 Python 2.7 中引入.对于 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.
这篇关于运行 python 包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!