解决subprocess.Popen执行脚本时无法导入template模块的问题
解决template模块找不到的问题
以下是几种可行的解决方式,按需选择:
方法1:手动添加模块路径到sys.path
在script.py中切换工作目录后,将目标目录加入Python的模块搜索路径,确保能找到template模块:import os import sys os.chdir('/user/document/test1/') # 把当前工作目录添加到sys.path sys.path.append(os.getcwd()) exec('from template.test import test_dict') print(test_dict)也可以直接写死绝对路径
sys.path.append('/user/document/test1/'),避免切换目录带来的不确定性。方法2:替换exec为常规导入
如果不是必须用exec,直接用正常导入语句,配合路径配置更稳妥:import sys sys.path.append('/user/document/test1/') from template.test import test_dict print(test_dict)方法3:在subprocess调用时指定工作目录
修改run.py的subprocess调用,直接指定script.py的执行工作目录为/user/document/test1/,这样script.py无需切换目录,Python会自动识别当前目录下的模块:
run.py代码:import subprocess subprocess.Popen(['python', '/user/document/home/script.py'], cwd='/user/document/test1/')script.py简化为:
from template.test import test_dict print(test_dict)方法4:用importlib动态加载模块(替代exec)
如果需要动态加载模块,用importlib比exec更规范,也不依赖模块搜索路径:import importlib.util # 直接指定test.py的绝对路径 test_file = '/user/document/test1/template/test.py' spec = importlib.util.spec_from_file_location('template.test', test_file) test_mod = importlib.util.module_from_spec(spec) spec.loader.exec_module(test_mod) test_dict = test_mod.test_dict print(test_dict)
内容的提问来源于stack exchange,提问作者bad_coder9042093
相关产品推荐
相关产品推荐

