简体   繁体   English

从python中的不同包导入文件时出现相对导入错误

[英]relative import error while importing file from diffrent package in python

I created the following directory structure.我创建了以下目录结构。

package1/
   __init__.py
   file1.py
   file2.py
package2/
   __init__.py
   utils.py

I have to import utils.py from package2 at file2.py in package1.我必须在 package1 的 file2.py 中从 package2 导入 utils.py。 I tried using我尝试使用

from .package2 import utils

but got error但有错误

ModuleNotFoundError: No module named '__main__.package2'; '__main__' is not a package 

In file2 you can add the root directory of package1 and package2 to your path:file2中,您可以将package1package2的根目录添加到您的路径中:

import os, sys
this_dir, _ = os.path.split(__file__)
root_dir = os.path.dirname(this_dir)
sys.path.append(root_dir)

Then import:然后导入:

from package2 import utils 

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

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