zoukankan      html  css  js  c++  java
  • Python 钩子函数详解

    ###### 钩子函数
    
    ```
    import pluggy
    
    hookspec = pluggy.HookspecMarker('aaa')
    hookimpl = pluggy.HookimplMarker('aaa')
    
    
    class MySpec():
    
    @hookspec() # firstresult=True设置之后,等到第一个返回非空结果的hookimpl,就返回(hookwrapper还是正常执行)
    def myhook(self, arg_one, arg_two):
    pass
    
    
    class MyPlugin():
    
    @hookimpl() # tryfirst=True,trylast=True定义执行顺序
    def myhook(self, arg_one):
    print('arg_one')
    return arg_one
    
    
    class MyPluginOther():
    
    @hookimpl()
    def myhook(self, arg_one, arg_two):
    print('arg_one, arg_two')
    return arg_one, arg_two
    
    
    class MyPluginWrapper():
    '''
    hookwrapper作为每个钩子函数的上下文运行
    在所有hook之前先运行
    '''
    @hookimpl(hookwrapper=True)
    def myhook(self):
    print('-------- hool wrapper before -----------')
    
    outcome = yield # 生成器会给outcome send一个pluggy.callers._Result对象
    
    print('-------- hook wrapper after -----------')
    res = outcome.get_result() # 通过get_result拿到所有钩子函数的结果
    print('get all hook return ', res)
    outcome.force_result(1) # 强制更改钩子函数返回结果
    
    print('-------- hook wrapper end-----------')
    
    
    test1 = pluggy.PluginManager('aaa')
    test1.add_hookspecs(MySpec)
    
    test1.register(MyPlugin())
    test1.register(MyPluginOther()) # 后注册的先执行,收集进结果
    test1.register(MyPluginWrapper())
    
    result = test1.hook.myhook(arg_one=1, arg_two=2) # hookimpl调用,必须用关键字语法
    print(result)
    
    ------------------
    输出结果:
    -------- hool wrapper before -----------
    arg_one, arg_two
    arg_one
    -------- hook wrapper after -----------
    get all hook return [(1, 2), 1]
    -------- hook wrapper end-----------
    1
    ```
  • 相关阅读:
    https进行配置以及http跳转到https配置
    centos7修改系统语言为简体中文
    iptables snat 和dnat说明
    python多线程执行类中的静态方法
    python 磁盘空间操作
    python logging 工具
    python 动态调用函数
    python 读写XML
    js加载json数据成表格
    python 比较两个数据库postgresql
  • 原文地址:https://www.cnblogs.com/EmptyRabbit/p/12377676.html
Copyright © 2011-2022 走看看