Python如何从包含无限while循环的函数中传递数据到main函数
问题核心原因
- 带
yield的receive()是生成器对象,直接调用不会执行内部代码,必须通过next()调用或者迭代才会触发运行、拿到yield返回的值 - 你写的
pass_return函数没有return语句,调用后永远返回None,无实际作用 - 若要在函数内部修改全局变量
confirmation,必须添加global confirmation声明,否则修改的是函数内部的局部变量,全局变量不会被更新
解决方案
方案1:使用yield实现(无需全局变量)
直接去掉没用的pass_return函数,初始化一次生成器后,每次需要取状态时调用next()即可:
import time # 你的原有常量、socket初始化代码 client = ... # 你的socket实例 FORMAT = "utf-8" # 你的自定义编码 def receive(): while True: try: incoming = client.recv(2048).decode(FORMAT) print(incoming) if 'RECEIVED:COMPLETE' in incoming: yield 'confirmed' else: yield 'unconfirmed' except: print("Connection interrupted.") client.close() break def main(): # 仅初始化一次生成器,不要每次发消息都重新调用receive() recv_gen = receive() # 其余原有业务代码 something = True # 你的原有判断条件 if something == True: send("some message") # 你的原有发送函数 time.sleep(.25) try: # 调用next触发生成器执行,拿到yield返回的状态 confirmation = next(recv_gen) if confirmation == 'confirmed': # 此处执行你需要的业务逻辑 print("确认收到,执行业务") # 接收线程断开时生成器会抛出停止异常,捕获即可 except StopIteration: print("接收连接已断开") return if __name__ == '__main__': main()
方案2:全局变量+多线程实现(无需yield)
如果你更习惯用全局变量的方式,直接开个后台线程跑接收逻辑即可:
import time import threading # 全局变量定义 confirmation = "" client = ... # 你的socket实例 FORMAT = "utf-8" # 你的自定义编码 def receive(): global confirmation # 必须加这行声明使用全局变量 while True: try: incoming = client.recv(2048).decode(FORMAT) print(incoming) if 'RECEIVED:COMPLETE' in incoming: confirmation = 'confirmed' else: confirmation = 'unconfirmed' except: print("Connection interrupted.") client.close() break def main(): # 开后台线程跑接收逻辑,不会阻塞主业务执行 recv_thread = threading.Thread(target=receive, daemon=True) recv_thread.start() # 其余原有业务代码 something = True # 你的原有判断条件 if something == True: send("some message") # 你的原有发送函数 time.sleep(.25) if confirmation == 'confirmed': # 此处执行你需要的业务逻辑 print("确认收到,执行业务") if __name__ == '__main__': main()
内容的提问来源于stack exchange,提问作者liquidRock
相关产品推荐
相关产品推荐

