Python - 如果 1 分钟内没有任何反应,继续执行代码

Python - If nothing happens for 1 minute, proceed code

我正在编写一个脚本,该脚本通过 websocket 向设备发送串行消息。当我想启动我写的设备时:

def start(ws):
    """
    Function to send the start command
    """
    print("start")
    command = dict()
    command["commandId"] = 601
    command["id"] = 54321
    command["params"] = {}
    send_command(ws, command)

设备每 5 小时左右重启一次,在重启期间,我的功能启动请求没有 运行 并且我的代码完全停止。

我的问题是,有没有办法告诉 python:“如果 1 分钟内没有任何反应,请重试”

您可以使用 time 模块中的 sleep

import time
time.sleep(60) # waits for 1 minute

此外,请考虑 Multithreading sleep

import threading 
import time
  
def print_hello():
  for i in range(4):
    time.sleep(0.5)
    print("Hello")
  
def print_hi(): 
    for i in range(4): 
      time.sleep(0.7)
      print("Hi") 

t1 = threading.Thread(target=print_hello)  
t2 = threading.Thread(target=print_hi)  
t1.start()
t2.start()

上面的程序有两个线程。已使用time.sleep(0.5)和time.sleep(0.75)分别暂停这两个线程的执行0.5秒和0.7秒。

more here

不清楚 ws 到底是什么,也不清楚您是如何设置它的;但您想为套接字添加超时。

https://websockets.readthedocs.io/en/stable/api.html#websockets.client.connect 有一个 timeout 关键字;有关其功能的详细信息,请参阅文档。

如果这不是您正在使用的 websocket 库,请使用详细信息更新您的问题。