如何在Python中使用importlib从父目录导入?

2024-03-28 20:11:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个目录:

Project Folder
├─main.py
├─Utils
│  └─util1.py
└─Plugins
   └─plugin1.py

如何直接从plugin1.py导入util1.py?我尝试使用importlib.import_module('Utils.util1', '..'),但没有成功from ..Utils import util1和{}也不起作用(ValueError: attempted relative import beyond top-level package

请注意:我的目录中没有UTIL和插件,我只是简单地在这里这样命名它们


Tags: frompyimport目录projectmainpluginsutils
2条回答

您可以这样做:
未经测试

import os, sys
currentDir = os.getcwd()
os.chdir('..') # .. to go back one dir | you can do "../aFolderYouWant"
sys.path.insert(0, os.getcwd())
import mymodule
os.chdir(currentDir) # to go back to your home directory
# From http://stackoverflow.com/a/11158224

# Solution A - If the script importing the module is in a package
from .. import mymodule

# Solution B - If the script importing the module is not in a package
import os,sys,inspect
current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parent_dir = os.path.dirname(current_dir)
sys.path.insert(0, parent_dir) 
import mymodule

相关问题 更多 >