current position:Home>Importlib.exe in Python import_ Module import module

Importlib.exe in Python import_ Module import module

2022-05-15 02:38:13Koki can test a rookie

1、 File structure :

├── clazz
│   ├── __init__.py
│   ├── a.py
│   └── b.py
└── main.py

a.py Code for

def show():
    print("show A")

b.py Code for

def show():
    print("show B")

from main Import clazz In bag a and b modular
main.py

import importlib

#  Absolutely import 
a = importlib.import_module("clazz.a")
a.show()
#  Print the results :show A

#  Relative Import 
b = importlib.import_module(".b", "clazz")
b.show()
#  Print the results :show B

Be careful , There is one point relative to import ., Similar path .

2. Set... Under a certain file :
File structure :

│──web_ui_auto_lib
│	├── element_behavior_handlers
│	│   ├── __init__.py
│	│   ├── check_behavior_handler.py
│	│   └── click_behavior_handler.py
│	│   └── close_behavior_handler.py
│	│   └── f5_behavior_handler.py
│	└── main.py

main.py Under the document :

# step.Behavior  Is the name of the traversal step :[check,click,close,f5]
module_name = "web_ui_auto_lib." + "element_behavior_handlers." + step.Behavior + "_behavior_handler"  
#  Every py The class name in the file is marked with  [check,click,close,f5] + BehaviorHandler
class_name = step.Behavior + "BehaviorHandler"
module = importlib.import_module(module_name)
#  Objects can be referenced  module_name  file  +  Class name ,
#  all check_behavior_handler.py,click_behavior_handler.py,close_behavior_handler.py,f5_behavior_handler.py It's all under the file  handle_behavior  This method 
aclass = getattr(module, class_name)
time.sleep(int(step.WaitTime))
handle_behavior = getattr(aclass, "handle_behavior")
returnvalue = handle_behavior(aclass(), self.bm, step)

copyright notice
author[Koki can test a rookie],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/132/202205120517584817.html

Random recommended