python用法随笔

1. 简介

自认为的高深用法总结

2. 运算条件 + 闭包

2.1 知识点

运算条件: operator.py

闭包 = 嵌套函数 + 外部变量

2.2 场景

“大于5发送201” :  闭包函数("大于", 5, 201)

“大于等于1发送200”: 闭包函数("大于等于", 1, 200)

 2.3 定义闭包

def 闭包(op, v, c):
    ops = dict()
    def 闭包_real(arg)
# 基准值     
if ops[op](v,b):      c
其他业务(arg)
return 闭包_real return 闭包

# 路由函数:
"条件1,大于5发送200": {
"me_fuc": 闭包("大于", 5, 200)
},
"条件2,等于1发送201": {
"me_func": 闭包("大于等于", 1, 201)
},

 

3 try + traceback + logging

traceback.format_exc() 与 traceback.print_exc() 区别:
   traceback.format_exc() 返回异常信息的字符串,可以用来把信息记录到log里;
   traceback.print_exc() 直接把异常信息在终端打印出来;
或者
   traceback.print_exc(file=open('traceback_INFO.txt','w+'))

配套

   def me_function(self, time_out, last_step_res):
        _res = 1
        try:
            if last_step_res != "success":
                raise Exception("上一步失败({0}),退出本次".format(last_step_res))

            # 超时退出
            eventlet.monkey_patch()
            with eventlet.Timeout(time_out, False):
                业务
            _res = 0
    
        except Exception as e:
            traceback.print_exc()
            e1 = str(traceback.format_exc())

        finally:
            return _res

 

posted @ 2021-09-07 16:16  fly_pig  阅读(32)  评论(0编辑  收藏  举报