超时跳过、接收子线程结果
方式一:eventlet 模块 缺点:针对子进程无法跳出
import time, eventlet
eventlet.monkey_patch()
with eventlet.Timeout(3, False):
time.sleep(4) # 可能超时的代码块
print('没有跳过')
方式二:
def demo():
time.sleep(3) # 可能超时的代码块
return time.time()
class MyThread(threading.Thread):
def __init__(self, func, args=()):
super(MyThread, self).__init__()
self.func = func
self.args = args
def run(self):
self.result = self.func(*self.args)
def get_result(self):
try:
return self.result
except Exception:
return None
t = MyThread(demo, ())
t.setDaemon(True)
t.start()
t.join(timeout=5)
x = t.get_result()
print(x)
与机器交互,获取结果
while True:
for i in range(3):
try:
time.sleep(3) # 接收数据
break_flag = False
break
except:
break_flag = True
print('接收阻塞,可能已经完成')
if break_flag: # 判定结果接收完毕,退出循环
break