在OSX上运行Python2.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在这一点上,我迷路了。为什么是non-package?那么如何组织代码呢?
发布于 2011-07-09 05:53:12
在Python2.7中引入了在使用命令行-m选项时运行包的__main__模块的特性。对于2.6版本,您需要指定要运行的包模块名称;-m test.__main__应该可以工作。请参阅文档here。
https://stackoverflow.com/questions/6630822
复制相似问题