Dynamic Import Module
For example, I want to introduce a file at the end of all ". Py" files in a folder, but I don't need to introduce _init_.py.
First, we get a related array of strings through the Python string processing process.
The source code is as follows:
Import OS
N=[]
Dir1=os.listdir (' E:\ \webtest\test_case ')
for a in Dir1:
M=a.find ("Start")
if m!=-1:
Test=a.split ('. ') [1]
if test==' py ':
Test1=a.split ('. ') [0]
N.append (test1)
At this point the N output is a string-form list:
n=[' start_01 ', ' start_02 ', ' start_03 ', ' start_04 ']
At this point, if you want to import dynamically, use the _import_ () method, and refer to the official guidance document for the use of this method.
The source code is as follows:
Range (0,M):
A="Test_case" +"." +n[i]
Load=__import__ (a)
By looping we import the module that we want to test in turn.
Dynamic Import Class
We test_case the folder underground, we need to dynamically get start_01 to the Start_04 folder under the corresponding class, this piece for easy invocation, our file name and class name are consistent.
The idea is as follows: First we get the premise of the class, is to obtain the module, just a dynamic import module, and did not get import module.
Get the following source code:
Test2=[]
Range (0,M):
A="Test_case" +"." +n[i]
Load=__import__ (a)
A=getattr (Load,n[i]) #获取module
B=getattr (A,n[i]) #获取class
Test2.append (b)
This section of the source code completes the process of dynamically acquiring classes.
For the use of the GetAttr method, refer to the official website documentation for details.
Python's dynamic import module and class