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

问题描述

我有一个这样的目录:

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

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

请注意:它不是我的目录中的utils和插件,为方便起见,我只是这样命名它们。

解决方法

# 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
,

你可以这样做:
未测试

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