2011-07-08 27 views
17

在OSX上运行Python 2.6.1,将部署到CentOS。想有一个包从一个命令行调用是这样的:运行python包

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 -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?那么如何构造代码呢?

+1

不是一个重复,与[-m]运行时不同的反应,不同的解决方案。即使听起来很接近。这个问题在运行时未能添加'.__ main__',另一个没有正确添加它。 –

回答

28

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

+1

太好了,谢谢! 2.6x的文档有点模糊,不同版本之间的混淆并没有帮助。 –

+0

//,这也是一个类似'python -m pip install argparse'之类的语句的问题。 –