Python 动态引入模块

[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 loading functions.

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值