本文介绍了Python3:尝试以非包形式进行相对导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很抱歉这个基本问题,因为它类似于以下内容:受相对进口困扰

I'm so sorry about this basic question, because it's similar to this:Stumped by relative imports

但是我正在尝试遵循PEP328 http://www.python.org/dev/peps /pep-0328/#guido-s-decision 它对我不起作用:(

But I'm trying to follow the PEP328http://www.python.org/dev/peps/pep-0328/#guido-s-decisionand it doesn't work for me :(

这些是我的文件:

dev@desktop:~/Desktop/test$ ls
controller.py  __init__.py  test.py

2to3说的没问题:

2to3 says all it's right:

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$

感谢您的帮助!预先感谢!

Any help is appreciated! Thanks in advance!

推荐答案

您不能在包中使用脚本 ;您正在运行test不是 test.test.因此,顶层脚本不能使用相对导入.

You cannot use a script within a package; you are running test, not test.test. A top-level script can thus not use relative imports.

如果您想以脚本的形式运行软件包,则需要将test/test.py移至testpackage/__main__.py,将shell中的一个目录上移至~/Desktop,并告诉python使用python -m testpackage运行软件包

If you wanted to run a package as a script, you'd need to move test/test.py to testpackage/__main__.py, move one directory up in your shell to ~/Desktop and tell python to run a package with 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已经为测试套件提供了这样一个程序包,可以在找到当前工作目录中的程序包之前找到它.

You cannot name the package test; Python already has such a package for the test suite and that'll be found before a package in the current working dir is found.

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

The alternative is to create a script outside of the package and import the package from the script.

这篇关于Python3:尝试以非包形式进行相对导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 12:45