在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
?那麼如何構造代碼呢?
不是一個重複,與[-m]運行時不同的反應,不同的解決方案。即使聽起來很接近。這個問題在運行時未能添加'.__ main__',另一個沒有正確添加它。 –