运行一个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
这时我迷路了.为什么选择non-package
?以及如何构建代码呢?
At this point I am lost. Why non-package
? And how to structure the code then?
推荐答案
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.
这篇关于运行一个python包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!