function definition
__import__ (name, globals={}, locals={}, fromlist=[], level=-1), moduleimport a module. Because This function was meant for use by the Pythoninterpreter and not for general use it was better to Useimportlib.impor T_module () To programmatically import a module. The Globals argument was only used to determine the Context;they was not modified. The locals argument is unused. The fromlistshould is a list of names to emulate "from name import ...", or Anempty list to emulate ' import name '. When importing a module from a package, note that __import__ (' a.b ', ...) Returns package A when fromlist are empty, but their submodule B whenfromlist is not empty. Level are used to determine whether to perform absolute or relative imports. -1 is the original strategy of Attemptingboth absolute and relative imports, 0 is absolute, a positive numberis the number Of the parent directories to search relative to the current module.
Name : reference module name, e.g. ' sys ', ' libs/module.a '
fromlist: sub-module list, if name is A.B format, you must add B to fromlist
Use
Example
import osdef test(): =__import__(‘datetime‘) print datetime.datetime.now() =__import__("module.module_a"globals=locals={}, fromlist=["module_a"], level=-1) print a.sub(x, y)test()
Calling modules of different directories
- You should sys.path.append (the path to the module) before referencing it with a relative path
Cases:
In the following example, due to the celery call, the running path is different from the current path, the direct reference to Module.module_a will be error: Unable to find the module, and if the first parameter of __import__ with an absolute path, will be an error: cannot use file name reference
The correct way is to first include the current path in the system path and then reference it with a relative path
fromCeleryImportCeleryImportOsImportSyscurrent_path=Os.path.dirname (Os.path.realpath (__file__)) Sys.path.append (Current_path) app=Celery (' Tasks ', backend=' AMQP ', Broker=' Amqp://test:[email protected]/testhost ')@app. TaskdefAdd (x, y): a= __import__("Module.module_a",Globals={},Locals={}, FromList=["Module_a"], Level=-1)PrintA.add (x, y)
"Python" __import__