Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python动态导入_Python_Python 2.7_Python Import - Fatal编程技术网

Python动态导入

Python动态导入,python,python-2.7,python-import,Python,Python 2.7,Python Import,我有一个元组列表,比如[(module\u name,module\u abs\u path)(mod2,path2),…] 模块位于脚本所在的“模块”子目录中。我试图编写一个脚本,读取conf文件,并从modules dir将conf文件中的一些变量提供给模块。我的意图是从这个脚本加载并运行所有模块,这样他们就可以访问这些变量 到目前为止我尝试过但失败的事情: 尝试使用\uuuuu import\uuuuuu(),但它表示不允许按文件名运行 尝试了导入lib.import_module(),但

我有一个元组列表,比如
[(module\u name,module\u abs\u path)(mod2,path2),…]

模块位于脚本所在的“模块”子目录中。我试图编写一个脚本,读取conf文件,并从modules dir将conf文件中的一些变量提供给模块。我的意图是从这个脚本加载并运行所有模块,这样他们就可以访问这些变量

到目前为止我尝试过但失败的事情:

  • 尝试使用
    \uuuuu import\uuuuuu()
    ,但它表示不允许按文件名运行
  • 尝试了导入lib.import_module(),但出现了相同的错误

  • 我应该如何执行此操作?

    在导入之前是否已尝试修复路径

    from __future__ import print_function
    import importlib
    import sys
    
    def import_modules(modules):
        modules_dict = dict()
        for module_name, module_path in modules:
            sys.path.append(module_path)  # Fix the path
            modules_dict[module_name] = importlib.import_module(module_name)
            sys.path.pop()                # Undo the path.append
        return modules_dict
    
    if __name__ == '__main__':
        modules_info = [
            ('module1', '/abs/path/to/module1'),
        ]
    
        modules_dict = import_modules(modules_info)
        # At this point, we can access the module as
        # modules_dict['module1']
        # or...
    
        globals().update(modules_dict)
        # ... simply as module1
    

    提供列表中项目的示例。你把什么作为
    \uuuu import\uuu()
    的参数?元组:('test\u printer','/Users/./../../..//modules/test\u printer.mod.py')imported=\uu import\uu('modules.+tuples[0]+'.mod')。此外,我还将modules dir标记为一个包,方法是在其中放置一个空的uu init_uu()文件。是否需要调用您的模块
    “module\u name.mod”
    ?如果不是,我想这可能是问题的根源。试着用下划线替换点,可能是我的名字有问题。感谢@leva7在函数import_modules中,最好使用{}而不是dict()