简体   繁体   English

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

[英]How to import from parent directory using importlib in Python?

I have a directory like this:我有一个这样的目录:

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

How can I import util1.py directly from plugin1.py?如何直接从 plugin1.py 导入 util1.py? I tried using importlib.import_module('Utils.util1', '..') , but that didn't work.我尝试使用importlib.import_module('Utils.util1', '..') ,但这没有用。 from ..Utils import util1 and from .. import Utils.util1 also did not work ( ValueError: attempted relative import beyond top-level package ) from ..Utils import util1from .. import Utils.util1也不起作用( ValueError: attempted relative import beyond top-level package

Please note: its not utils and plugins in my directory, I just named them like that here for ease.请注意:它不是我的目录中的实用程序和插件,为了方便起见,我只是在此处将它们命名为这样。

# 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

you could do:你可以这样做:
not tested未测试

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

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

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