python获取threading+client+全局变量的返回值

是的,就是遇到了这么个棘手的问题(也是因为我菜)
要在线程里通过client调取服务器数据定时刷新,然后还要返回这个结果。但是我不是陷入import cycle就是这个没有那个的问题,最后突然灵机一动,成了

感谢这位老哥的文章给予的莫大支持

要想获取线程中执行方法return的返回值,就需要重新定义 threading 的类,不仅需要继承还要把我们的client放进去
result是我们通过client获取到的数据,并且是一个global变量
如果想要获取result的值只需通过Thread.get_result()就可以。


thread_lock = threading.Lock()

class Thread(threading.Thread):
    def __init__(self, client):
        super(CheckThread, self).__init__()
        self.client = client
        
	def run(self):
        print("Thread creating")
        while True:
            try:
                with thread_lock:
                    global result
                    result = do_something(self.client)
                    if not result:
                        raise Exception
                    
            except Exception as e:
                traceback.print_exc(e)
                print("cache refresh failed")
                
            # 间隔一小时
            sleep(3600)
            
	@staticmethod
    def get_result():
        try:
            return result
        except Exception:
            return None

@staticmethod真香
如果get_result不用staticmethod的话,

    def get_result(self):
        try:
            return result
        except Exception:
            return None

那我们要获取result时必须是Thread.get_result(client),然后会报错client没有_initialized等等等
其实这也是我自己之前陷入的误区,想着要从外面可以直接获取到全局变量result

另外一个需要注意的地方是请将这个class单独写到另一个py文件中,需要的时候再import,不然就会陷入import的cycle

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值