nfcpy:无法逃脱 while 循环,不断地用 nfcpy 收听

nfcpy: Can't escape a while loop constantly listening with nfcpy

我目前有一个 python 脚本,当标签通过 ACR122U reader 传递时,我使用 nfcpy 来监听和处理。最终目标是在扫描标签时监听并键入标签的 UID。我已经让那部分工作了。

我遇到的问题是,为了让程序在第一个标签被扫描后不结束,我包围了下面一行 - 它启动 reader 并让它监听一个标记 - 包围在 while true 循环中:

with nfc.ContactlessFrontend('usb') as clf: tag = clf.connect(rdwr=rdwr_options)

但是,点击 ^C 不会让程序在等待标签时退出。当上面提到的行没有被 while 循环包围时,它确实可以终止程序。

我试过将它包装在 try 块中并添加键盘中断异常,但这没有任何作用。

到目前为止,这是我的代码:

import nfc
import time
import os

def typestr(text,returnatend):
    totype = text
    if returnatend=="false":
        cmd = """osascript -e 'tell application "System Events"' -e 'delay 0.1' -e 'keystroke "%s"' -e 'end tell' -e 'delay 2.0'""" % totype
    else:
        cmd = """osascript -e 'tell application "System Events"' -e 'delay 0.1' -e 'keystroke "%s"' -e 'delay 0.1' -e 'key code 36' -e 'end tell' -e 'delay 2.0'""" % totype

    os.system(cmd)

def notification_osx(text,title,subtitle):
    cmd = """osascript -e 'display notification "%s" with title "%s" subtitle "%s"'""" % (text, title, subtitle)
    os.system(cmd)

def on_startup(targets):
    for target in targets:
        target.sensf_req = bytearray.fromhex("0012FC0000")
    return targets

def on_connect(tag):
    print("printing tag")
    print(tag)
    print("printing uid")
    uid = str(tag.identifier).encode("hex").upper()
    typestr(uid,"false")
    notification_osx(uid,"Scanned Card", "Scanned a card with ID:")


rdwr_options = {
    'on-startup': on_startup,
    'on-connect': on_connect,
    'beep-on-connect': False,
}

while True:
    with nfc.ContactlessFrontend('usb') as clf:
        tag = clf.connect(rdwr=rdwr_options)

clf.connect 方法 returns False 当被 Ctrl-C 中断时。您的代码应该评估 return 值并在 tag is False 时中断循环。这在 ContactlessFrontend.connect 描述末尾的 Return 值 下记录。