This article summarizes the Python dynamic Load package method. Share to everyone for your reference, as follows:
There are three ways to load modules dynamically
1. Using the system function __import_ ()
Stringmodule = __import__ (' string ')
2. Using the Imp module
Import Imp stringmodule = Imp.load_module (' String ', *imp.find_module (' string ')) Imp.load_source ("Tyacmgrhandler_" + App.upper (), filepath)
3. Use the Exec
import_string = "Import string as Stringmodule" exec import_string
Whether a variable exists
1. Hasattr (Test, ' t ')
2. ' Var ' in locals (). Keys ()
3. ' Var ' in Dir ()
4. VARs (). Has_key (' s ')
Dynamically increasing properties
Class Obj (object): passdef 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.cif __name__ = = ' __main__ ': Main ()
Dynamic Load Package:
def test (s,e): print s print Eclass C (): def __init__ (self,name): print name def test (self): print ' class!!! '
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:d yn=dynload (' Util.common ', [' * ']) ins=dyn.getclassinstance (' C ', ' Gao ') Dyn.execmethod (INS, ' Test ') dyn.execfunc (' Test ', ' Hello ', ' function! ')
Load the specified file by name
def Loadapp (self, app): filepath= "mgr/" +app+ ". Py" if Os.path.exists (filepath): Imp.load_source (" Tyacmgrhandler_ "+app.upper (), filepath)//Modify the app.py, call this function from the new code automatically
Call the corresponding method according to the name
Return GetAttr (Self, op) (Args.get ("Port"), args)//op= ' start ' args=dictgetattr (self, Self.request.method.lower ()) (* args, **kwargs)