运行 python 包
在 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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.