Home > Backend Development > Python Tutorial > Detailed introduction to the method of dynamically loading packages in Python

Detailed introduction to the method of dynamically loading packages in Python

高洛峰
Release: 2017-03-04 16:42:01
Original
1575 people have browsed it

The example in this article summarizes the method of dynamically loading packages in Python. Share it with everyone for your reference, the details are as follows:

There are three ways to dynamically load modules

1. Use the system function __import_()

stringmodule = __import__('string')
Copy after login

2. Use imp module

import imp 
stringmodule = imp.load_module('string',*imp.find_module('string'))
imp.load_source("TYACMgrHandler_"+app.upper(), filepath)
Copy after login

3. Use exec

import_string = "import string as stringmodule"
exec import_string
Copy after login

Whether the variable exists

1. hasattr(Test,'t')
2. 'var' in locals ().keys()
3. 'var' in dir()
4. vars().has_key('s')

Dynamicly add attributes

class Obj(object):
  pass
def main():
  list=["a","b", "c"]
  for i inrange(1,len(list),2):
    Obj = type('Obj',(),{list[i]:lambdaself,s:obj.__setattr__(s.split(" = ")[0],s.split(" = ")[1])})
  obj =Obj()
  for i inrange(0,len(list),2):
    obj.__setattr__(list[i],list[i])  
  obj.a =1
  obj.b("a =2")
  obj.b("c =3")
  printobj.a
  printobj.c
if __name__ == '__main__':
  main()
Copy after login

Dynamic loading package:

def test(s,e):
  print s
  print e
class C():
  def __init__(self,name):
    print name
  def test(self):
    print 'class!!!'
Copy after login

Loader code:

class Dynload():
  def __init__(self,package,imp_list):
    self.package=package
    self.imp=imp_list
  def getobject(self):
    return __import__(self.package,globals(),locals(),self.imp,-1)
  def getClassInstance(self,classstr,*args):
    return getattr(self.getobject(),classstr)(*args)  
  def execfunc(self,method,*args):
    return getattr(self.getobject(),method)(*args)
  def execMethod(self,instance,method,*args):
    return getattr(instance,method)(*args)
#Test:
dyn=Dynload('util.common',['*'])
ins=dyn.getClassInstance('C','gao')
dyn.execMethod(ins,'test')
dyn.execfunc('test','Hello','function!')
Copy after login

Load the specified file according to the name

def loadapp(self, app):
    filepath="mgr/"+app+".py"
    if os.path.exists(filepath):
      imp.load_source("TYACMgrHandler_"+app.upper(), filepath)
//修改了app.py,从新调用这个函数,新的代码自动生效
Copy after login

Calling the corresponding method according to the name

return getattr(self, op)(args.get("port"), args) //op="start" args=dict
getattr(self, self.request.method.lower())(*args, **kwargs)
Copy after login

For more detailed introduction to the method of dynamically loading packages in python, please pay attention to the PHP Chinese website for related articles. !

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template