【问题标题】:Python3: Attempted relative import in non-packagePython3:尝试在非包中进行相对导入
【发布时间】:2014-01-02 03:45:16
【问题描述】:

对于这个基本问题,我很抱歉,因为它类似于: Stumped by relative imports

但我正在尝试关注 PEP328 http://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$ 

感谢任何帮助!提前致谢!

【问题讨论】:

    标签: python python-3.x importerror


    【解决方案1】:

    你不能在一个包使用脚本;你正在运行test不是 test.test。因此,顶级脚本不能使用相对导入。

    如果你想将包作为脚本运行,你需要将test/test.py移动到testpackage/__main__.py,将你的shell中的一个目录向上移动到~/Desktop,并告诉python使用python -m testpackage运行一个包.

    演示:

    $ 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 已经为测试套件提供了这样的包,并且会在找到当前工作目录中的包之前找到它。

    另一种方法是在包的外部创建一个脚本,然后从脚本中导入包。

    【讨论】:

      猜你喜欢
      • 2014-02-28
      • 2019-05-25
      • 1970-01-01
      • 2015-12-08
      • 2014-11-14
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多