Python dynamically imports modules in a folder
Because of the requirement of "User upload script, dynamic operation", we need to dynamically import the user upload Module
So I wrote a function to dynamically import
#-*-Coding: UTF-8-*-import osimport sysimport OS. pathimport Queueimport commandsdef test (rootDir): # determine whether the input path contains "_ init __. py "file. if it does not exist, it will be created; otherwise, import will think that this moudle if OS is not. path. exists (rootDir): arr = rootDir. spliplit ("/") pathDir = "" for path in arr: pathDir = pathDir + path + "/" if not OS. path. exists (pathDir + "/_ init __. py "): commands. getoutput ("touch" + pathDir + "/_ init __. py ") # traverse the folder to find The py file starting with app _ and import it, Note globals; otherwise, the scope is only in this function. list_dirs = OS. walk (rootDir) for dirName, subdirList, fileList in list_dirs: for f in fileList: file_name = f if file_name [0: 4] = "app _" and file_name [-3:] = ". py ": impPath =" "if dirName [-1:]! = "/": ImpPath = dirName. replace ("/",". ") [2:] else: impPath = dirName. replace ("/",". ") [2:-1] print dirName," \ n ", impPath if impPath! = "": Exe_str = "from" + impPath + ". "+ file_name [0:-3] +" import * "else: exe_str =" from "+ file_name [0:-3] +" import * "exec (exe_str, globals () test (". /app/inapp/") a = Printaa (). printha ()
./app/inapp/
There is an app_XXX.py file, which contains
Printaa class, used for testing