我正在编写一个python脚本,用于从另一个项目导入设置文件
这是项目的结构:
- root
- ...
- folder_1
- setting_folder
- __init__.py
- setting_1.py
- setting_2.py
- setting_3.py
这里的文件内容:
init.py
from .setting_1 import *
from .setting_2 import *
setting_1.py
foo = "foo1"
设置2.py
foo = "foo2"
try:
from .setting_3 import *
except ImportError:
pass
setting_3.py
foo = "foo3"
我需要做的是,从项目外部的脚本中,加载setting_2.py并获取foo变量的值(由于相对导入,foo3(
假设我从目录"C: \用户\酒吧\桌面"。我实现这个目标的想法是将setting_2.py复制到项目外的另一个目录中(比如a(,在a中创建一个空文件init.py,附加到PYTHONPATH";C: \用户\酒吧\桌面"然后导入模块。
这里的代码:
import os
import importlib.util
with open(setting_2_path, "r") as f:
test_file_content = f.read()
setting_tmp_path = r"C:UsersbarDesktopasetting_2.py"
with open(setting_tmp_path, "w") as f:
f.write(test_file_content)
init_tmp_path = r"C:UsersbarDesktopa__init__.py"
with open(init_tmp_path, "w") as f:
f.write("")
current_env = os.environ.copy()
current_env.update({'PYTHONPATH': r"C:UsersbarDesktop"})
spec_module = importlib.import_module('a.setting_2')
print(getattr(spec_module, "foo"))
这运行得很好,但在生产中,这个脚本将在另一个项目中,我无法在脚本的同一级别创建文件夹
我可以在另一个目录中创建文件夹。
为了模拟这种情况,假设我从C:\Users\bar\Desktop\bar2运行脚本,文件夹是C:\Users\bar \Desktor\a。
在这种情况下,我有以下错误:
ImportError: No module named 'a'
我该如何解决这个问题?
import os
import sys
cwd = os.getcwd() # This is current working directory, as in your assumption it is: C:UsersbarDesktopbar2
path_to_settings_files = os.path.join(os.path.dirname(cwd), 'a') # This is where settings are, as in your assumption it is: C:UsersbarDesktopa
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)