How do I execute a string containing Python code in Python?

后端 未结 14 2407
一向
一向 2020-11-22 02:42

How do I execute a string containing Python code in Python?

14条回答
  •  死守一世寂寞
    2020-11-22 03:04

    Ok .. I know this isn't exactly an answer, but possibly a note for people looking at this as I was. I wanted to execute specific code for different users/customers but also wanted to avoid the exec/eval. I initially looked to storing the code in a database for each user and doing the above.

    I ended up creating the files on the file system within a 'customer_filters' folder and using the 'imp' module, if no filter applied for that customer, it just carried on

    import imp
    
    
    def get_customer_module(customerName='default', name='filter'):
        lm = None
        try:
            module_name = customerName+"_"+name;
            m = imp.find_module(module_name, ['customer_filters'])
            lm = imp.load_module(module_name, m[0], m[1], m[2])
        except:
            ''
            #ignore, if no module is found, 
        return lm
    
    m = get_customer_module(customerName, "filter")
    if m is not None:
        m.apply_address_filter(myobj)
    

    so customerName = "jj" would execute apply_address_filter from the customer_filters\jj_filter.py file

提交回复
热议问题