简体   繁体   English

为什么相对导入在Python 3中不起作用?

[英]Why don't relative imports work in Python 3?

I recently upgraded from python2.7 to python3 and think it may have screwed up some configurations. 我最近从python2.7升级到python3,并认为它可能搞砸了一些配置。 Now when I try to run a module, I get import errors. 现在,当我尝试运行模块时,出现导入错误。 Let's say I have a directory structure like this: 假设我有一个这样的目录结构:

/directory
/directory/__init__.py
/directory/run.py
/directory/app/db.py
/directory/app/views.py
/directory/app/__init__.py

with the following imports... 具有以下进口...

/directory/run.py says 'import app'
/directory/app/db.py says 'import views'

When I execute run.py, I get an error saying the module views cannot be found. 当我执行run.py时,出现一个错误,提示找不到模块视图。 However, if I go into /directory/app and execute db.py, then the import runs correctly. 但是,如果我进入/ directory / app并执行db.py,则导入将正确运行。 I've also found that if I change the /directory/app/db.py to say "from app import views" then it works correctly when executing run.py. 我还发现,如果我将/directory/app/db.py更改为“来自应用程序导入视图”,则在执行run.py时它可以正常工作。 However, this used to all work! 但是,这曾经用于所有工作!

It seems like the import statements are not taking into account the folder it's being executed in. It seems like this wants me to base all of my imports out of the root folder, which seems incorrect and would take me time to change everything. 似乎import语句没有考虑要在其中执行的文件夹。这似乎希望我将所有导入都基于根文件夹,这似乎是不正确的,需要我花费一些时间来更改所有内容。

Any ideas as to what happened? 有什么想法发生了什么? This has been driving me crazy. 这让我发疯。

In Python3, implicit relative imports have been removed, all imports need to be either absolute, or use explicit relative imports. 在Python3中,隐式相对导入已被删除,所有导入都必须是绝对导入,或使用显式相对导入。

This is not going to change, you need to either replace them with from app import views or from . import views 这不会改变,您需要将它们替换为from app import viewsfrom . import views from . import views . from . import views

Python 2.x and Python 3.x differ in so many ways it is usually extremely helpful to use 2to3 or another similar tool to "port" (convert) the code. Python 2.x和Python 3.x有很多不同之处,通常使用2to3或其他类似工具“移植”(转换)代码非常有帮助。

The issue you are running into likely has to do with the fact that Python 2 uses relative imports but Python 3 uses absolute imports (I may have that backwards). 您遇到的问题很可能与以下事实有关:Python 2使用相对导入,而Python 3使用绝对导入(我可能倒数了)。 It is possible to change the import statement to make the import work, though for the torrent of compatibility issues that will surely follow, I highly recommend using 2to3 and then making any final adjustments manually. 可以更改import语句以使导入工作,但是对于肯定会出现的兼容性问题,我强烈建议使用2to3,然后手动进行任何最终调整。

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM