强迫使用imp.find_模块从子目录

2024-05-17 20:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个项目:

main
|---src.py
|---frame_select.py
|-----shellsdir
      |---script_select.py
      |------scriptsdir
             |---test.py

Main有一个脚本,它将参数传递给frame_select.py,然后根据传递的参数在shelldir内部查找适当的脚本。它返回并使用:

^{pr2}$

shellsdir中大约有16个脚本,因此它根据传递的参数选择在shellsdir中加载哪个脚本。在shellsdir中是另一个名为scriptsdir的目录和一个文件script_selector。文件如下所示:

import imp, sys

sys.path.insert(0, '/path/to/scriptsdir/')

def module_import(mod_name):
   fp, p, d = imp.find_module(mod_name)
   py_mod = imp.load_module(mod_name,
                            fp,
                            p,
                            d)

本质上只是重用代码,但现在我指向scriptsdir,让程序向module_import()函数传递一个参数。但是,我没有得到ImportError: No module named 'name_passed'。在

我做了一个print sys.path/path/to/shellsdir/和{}都在那里。模块名匹配,所以我不确定为什么会出错。在


Tags: pathnamepyimport脚本mod参数sys
1条回答
网友
1楼 · 发布于 2024-05-17 20:38:19

帧_选择.py: 更新了src.py文件的相对路径。在

import imp, sys

sys.path.insert(0, './shellsdir')

def module_import(mod_name):
   fp, p, d = imp.find_module(mod_name)
   py_mod = imp.load_module(mod_name,
                            fp,
                            p,
                            d)

def pick(value, window):
   if value == 'name_passed':
      c_mod = module_import('specific_name')
      c_mod.populate(window)

对于脚本_选择.py: 更新了src.py文件的相对路径。在

^{pr2}$

值得注意的是,../scriptsdir/将不起作用。然而,我早就知道了,但是由于进口时间太长,我认为它不起作用。忘了我在test.py文件中有大约20个模块(用于测试目的),这就是导致延迟的原因。在

相关问题 更多 >