Python 动态引入模块
2014-11-01 19:26
162 查看
[xluren@test import_test]$ ll total 8 -rw-rw-r--. 1 xluren xluren 79 Nov 1 19:19 bar.py -rw-rw-r--. 1 xluren xluren 57 Nov 1 19:18 foo.py [xluren@test import_test]$ python bar.py 0 1 2 3 4 5 6 7 8 9 [xluren@test import_test]$ cat bar.py module_name="foo" plug_module=__import__(module_name) plug_module.print_foo() [xluren@test import_test]$ cat foo.py def print_foo(): for i in range(10): print i [xluren@test import_test]$As mentioned the imp module provides you loadingfunctions.imp.load_source(path)imp.load_compiled(path)I've used these before to perform something similar.In my case I defined a specific class with defined methods that were required. So, once I loaded the module I would check if the class was in the module, and then create an instance of that class.Something like this:
import imp import os def load_from_file(filepath): class_inst = None expected_class = 'MyClass' mod_name,file_ext = os.path.splitext(os.path.split(filepath)[-1]) if file_ext.lower() == '.py': py_mod = imp.load_source(mod_name, filepath) elif file_ext.lower() == '.pyc': py_mod = imp.load_compiled(mod_name, filepath) if hasattr(py_mod, expected_class): class_inst = getattr(py_mod, expected_class)() return class_inst
相关文章推荐
- python 动态引入模块 importlib 和 __import__ 不一样
- python技巧31[Python 动态加载模块的3种方法]
- Python 动态加载模块的3种方法
- 【python】 动态加载模块和类
- python中动态加载模块和类方法实现
- python - 动态加载模块和类
- 动态加载python可执行模块的办法(示例代码)
- Python动态加载模块
- Python 如何引入自定义模块
- python模块引入
- python引入自定义模块
- 在python中实现动态导入模块importlib.import_module
- python动态加载模块及变量是否存在方法
- python动态导入模块、判断模块是否已安装
- python 动态调用模块&类&方法
- python动态导入模块
- [转]Python动态导入模块
- python技巧31[Python 动态加载模块的3种方法]
- 使用random模块,生成动态随机密码 分类: python 小练习 python Module 2013-12-04 17:23 278人阅读 评论(0) 收藏
- Python 引入外部自定义模块