【问题标题】:How to import from parent directory using importlib in Python?如何在 Python 中使用 importlib 从父目录导入?
【发布时间】:2020-10-05 20:41:22
【问题描述】:

我有一个这样的目录:

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

请注意:它不是我目录中的实用程序和插件,为了方便起见,我只是在这里命名它们。

【问题讨论】:

  • sys.path中的顶级项目文件夹吗?
  • 试试from ... import utils.util1
  • @JohnGordon nope
  • @Goldwave 不起作用

标签: python python-3.x python-import python-importlib


【解决方案1】:
# 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

【讨论】:

  • 我如何知道它是否在一个包中?
  • 可能不是。我会尝试解决方案 B
【解决方案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

【讨论】:

    猜你喜欢
    • 2019-10-30
    • 2021-09-08
    • 2013-11-09
    • 2014-11-07
    • 1970-01-01
    • 2016-12-27
    • 2012-07-08
    • 2020-03-21
    • 2019-05-31
    相关资源
    最近更新 更多