【问题标题】:Import module with relative imports using importlib使用 importlib 导入具有相对导入的模块
【发布时间】:2021-07-16 08:53:00
【问题描述】:

我正在编写一个 python 脚本来从另一个项目中导入一个设置文件。
这是项目的结构:

- root
- ...
- folder_1
    - setting_folder
        - __init__.py
        - setting_1.py
        - setting_2.py
        - setting_3.py

这里是文件内容:

初始化.py

from .setting_1 import *
from .setting_2 import *

setting_1.py

foo = "foo1"

setting_2.py

foo = "foo2"

try:
    from .setting_3 import *
except ImportError:
    pass

setting_3.py

foo = "foo3"

我需要做的是,从项目外部的脚本中,加载 setting_2.py 并获取 foo 变量的值(由于相对导入导致 foo3)。
假设我从目录“C:\Users\bar\Desktop”运行我的脚本。 我实现这一目标的想法是将setting_2.py复制到项目外部的另一个目录中(比如说a),在a中创建一个空文件init.py,附加到PYTHONPATH“C:\Users\ bar\Desktop”,然后导入模块。

代码如下:

import os
import importlib.util

with open(setting_2_path, "r") as f:
   test_file_content = f.read()

setting_tmp_path = r"C:\Users\bar\Desktop\a\setting_2.py"
with open(setting_tmp_path, "w") as f:
    f.write(test_file_content)

init_tmp_path = r"C:\Users\bar\Desktop\a\__init__.py"

with open(init_tmp_path, "w") as f:
    f.write("")

current_env = os.environ.copy()
current_env.update({'PYTHONPATH': r"C:\Users\bar\Desktop"})

spec_module = importlib.import_module('a.setting_2')

print(getattr(spec_module, "foo"))

这运行良好,但在生产中,此脚本将位于另一个项目中,我无法在脚本的同一级别创建文件夹。
我可以创建文件夹,但在另一个目录中。

为了模拟这种情况,假设我从 C:\Users\bar\Desktop\bar2 运行脚本,文件夹是 C:\Users\bar\Desktop\a。

在这种情况下,我有以下错误:

ImportError: No module named 'a'

我该如何解决这个问题?

【问题讨论】:

  • 您是否尝试将目录附加到sys.path 然后加载?
  • 您的意思是“C:\Users\bar\Desktop”吗?那么pythonpath呢?
  • 让我与您分享我的想法,作为代码示例的答案。

标签: python python-3.x import path


【解决方案1】:
import os
import sys

cwd = os.getcwd()  # This is current working directory, as in your assumption it is: C:\Users\bar\Desktop\bar2

path_to_settings_files = os.path.join(os.path.dirname(cwd), 'a')  # This is where settings are, as in your assumption it is: C:\Users\bar\Desktop\a

sys.path.append(path_to_settings_files)  # This line guides interpreter to find settings.py in loading modules

import setting_1
import setting_2
import setting_3

print(setting_1.foo)
print(setting_2.foo)
print(setting_3.foo)

【讨论】:

  • 感谢您的回答。它不起作用,我有这个错误 SystemError: Parent module '' not loaded, cannot perform relative import
猜你喜欢
  • 2018-11-25
  • 2021-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 2016-11-13
相关资源
最近更新 更多