简体   繁体   English

如何使用IntelliJ处理Python中的相对导入

[英]How to deal with relative import in Python with IntelliJ

Similar questions have been asked many times, but I can't figure out how to solve it when using IntelliJ. 类似的问题已经问了很多遍,但我无法弄清楚在使用IntelliJ时该如何解决。

I have a directory like following 我有一个如下目录

package
├── init .py. ├── 初始化的.py。
├── subpackage1 ├──子包装1
│ ├── init .py │├── 初始化 .py
│ ├── moduleX.py │├──moduleX.py
├── subpackage2 ├──子包装2
│ ├── init .py │├── 初始化 .py
│ ├── moduleY.py │├──moduleY.py

In moduleY I want import moduleX using relative import syntax: from ..subpackage1 import moduleX moduleY我想导入moduleX使用相对导入语法: from ..subpackage1 import moduleX

and got the following error message: 并收到以下错误消息:

attempted relative import beyond top-level package 尝试相对顶级包进行相对导入

I know this can be solved by changing the working directory to the top of "package", and typing python -m package.subpackage2.moduleY in the console. 我知道可以通过将工作目录更改为“ package”的顶部并在控制台中键入python -m package.subpackage2.moduleY来解决此问题。

But how can I do it in IntelliJ? 但是我该如何在IntelliJ中做到呢?

Following should work: 以下应该工作:

import sys
from os import path
sys.path.append( path.dirname( path.dirname( path.abspath(__file__) ) ) )
from subPackage1 import fileInSubPackage1

Also, there is a very good explanation on how to deal with imports which can be found here 另外,关于如何处理进口货的解释也很好,可以在这里找到

UPDATE: 更新:

Having gone through the official documentation, I realized the reason for above relative import to fail is that when using from something import somefile something should be a package or a number of packages. 查阅了官方文档后,我意识到上述相对导入失败的原因是,当from something import somefile某文件时,某项应为一个包或多个包。 Below picture will clarify it further: 下图将进一步阐明它:

给定这个项目结构

if we have above project structure, and want to import the_program.py in file_random.py , we have to write from directory_one.package_inside_directory_one import the_program directory_one and package_inside_directory are both packages. 如果我们有上述项目结构,并要导入the_program.pyfile_random.py ,我们必须编写from directory_one.package_inside_directory_one import the_program directory_one和package_inside_directory都是包。 and from ..package_two_inside_directory_one import the_program will result in ValueError: attempted relative import beyond top-level package from ..package_two_inside_directory_one import the_program将导致ValueError: attempted relative import beyond top-level package

Now, if the structure is extended to below: 现在,如果结构扩展到下面:

项目结构扩展

and we're in the_program.py and want to import file_under_Subdirectory.py and more_tests.py we simply follow the same rule: 并且我们在the_program.py中,想要导入file_under_Subdirectory.pymore_tests.py我们只需遵循相同的规则:

from directory_two.package_inside_directory_two import more_tests
from directory_two.package_inside_directory_two.subDirectory_inside_package_two import file_under_Subdirectory

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

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