我对这个基本问题感到非常抱歉,因为它类似于:被相对进口所困扰
但我正在尝试遵循 PEP328http://www.python.org/dev/peps/pep-0328/#guido-s-decision这对我不起作用:(
这些是我的文件:
dev@desktop:~/Desktop/test$ ls
controller.py __init__.py test.py
2to3 说一切都是对的:
dev@desktop:~/Desktop/test$ 2to3 .
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: No files need to be modified.
文件内容:
dev@desktop:~/Desktop/test$ cat controller.py
class Controller:
def __init__(self):
pass
dev@desktop:~/Desktop/test$ cat __init__.py
# -*- coding: utf-8 -*-
dev@desktop:~/Desktop/test$ cat test.py
#!/usr/bin/env python
from .controller import Controller
if __name__ == '__main__':
print('running...')
但导入不起作用:
dev@desktop:~/Desktop/test$ python3 test.py
Traceback (most recent call last):
File "test.py", line 2, in <module>
from .controller import Controller
ValueError: Attempted relative import in non-package
dev@desktop:~/Desktop/test$
任何帮助表示赞赏!提前致谢!
您不能使用脚本within一套;你在跑步test
, not test.test
。因此,顶级脚本不能使用相对导入。
如果您想将包作为脚本运行,您需要移动test/test.py
to testpackage/__main__.py
,在 shell 中向上移动一个目录到~/Desktop
并告诉 python 运行一个包python -m testpackage
.
Demo:
$ ls testpackage/
__init__.py __main__.py __pycache__ controller.py
$ cat testpackage/controller.py
class Controller:
def __init__(self):
pass
$ cat testpackage/__init__.py
# -*- coding: utf-8 -*-
$ cat testpackage/__main__.py
from .controller import Controller
if __name__ == '__main__':
print('running...')
$ python3.3 -m testpackage
running...
您无法命名该包test
; Python 已经为测试套件提供了这样一个包,并且会在当前工作目录中找到包之前找到该包。
另一种方法是创建一个脚本outside包并从脚本导入包。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)