如何在设定时长后终止函数?树莓派NFC扫描输入超时问题求助
可在树莓派上实现NFC扫描超时终止的可行方案
以下方案均适配树莓派Linux运行环境,可直接替换你现有逻辑使用:
方案1:使用SIGALRM信号实现超时(轻量首选)
Linux系统原生支持闹钟信号,无需额外依赖,适配所有同步阻塞函数的超时控制:
import signal from contextlib import contextmanager class TimeoutException(Exception): pass @contextmanager def time_limit(seconds): def signal_handler(signum, frame): raise TimeoutException("Function execution timed out") # 注册信号处理函数 signal.signal(signal.SIGALRM, signal_handler) # 设置闹钟,到时间后发送SIGALRM信号触发超时 signal.alarm(seconds) try: yield finally: # 执行完成后取消闹钟,避免误触发 signal.alarm(0) # 调用示例 def wait_for_nfc_scan(): # 此处替换为你原本的NFC扫描阻塞逻辑 pass if __name__ == "__main__": try: with time_limit(10): # 自定义超时时长,此处示例为10秒 wait_for_nfc_scan() print("NFC扫描完成,正常返回") except TimeoutException: print("扫描超时,回到主逻辑继续执行")
注意:该方案仅适用于Unix/Linux环境,刚好匹配树莓派运行场景,如果你的程序本身有其他SIGALRM信号处理逻辑,可选择下方多线程方案
方案2:多线程超时控制(兼容性最强)
如果存在信号冲突、或你的NFC逻辑本身会启动子线程,可以用多线程+标志位实现超时:
import threading import time nfc_scan_result = None stop_scan_flag = False def wait_for_nfc_scan(): global nfc_scan_result while not stop_scan_flag: # 此处替换为你实际的非阻塞NFC轮询逻辑,每次轮询耗时建议不超过1秒 scan_res = 你的NFC检测函数() if scan_res is not None: nfc_scan_result = scan_res break time.sleep(0.1) # 调用示例 if __name__ == "__main__": scan_thread = threading.Thread(target=wait_for_nfc_scan, daemon=True) scan_thread.start() # 等待线程最多10秒 scan_thread.join(timeout=10) # 设置停止标志位,通知扫描线程终止 stop_scan_flag = True scan_thread.join() if nfc_scan_result is not None: print(f"扫描到NFC卡,数据为:{nfc_scan_result}") else: print("扫描超时,回到主逻辑继续执行")
注意:需要把原本的阻塞式NFC扫描逻辑改成轮询模式,绝大多数NFC读写库都支持非阻塞的单次卡检测方法
优化提示
如果你的NFC驱动库本身支持超时参数,直接使用库自带配置即可,比如常用的PN532驱动库pn532pi的read_passive_target方法自带timeout参数,直接设置对应值就能实现超时自动返回,是性能最好、稳定性最高的方案。
内容的提问来源于stack exchange,提问作者Jonathan-0101
相关产品推荐
相关产品推荐

