我目前有一个 python 脚本,当标签通过 ACR122U 阅读器时,我使用 nfcpy 来监听和处理。最终目标是在扫描标签时监听并键入标签的 UID。我已经让那部分工作了。
我遇到的问题是,为了让程序在第一个标签被扫描后不结束,我将下面一行包围起来——它启动阅读器并让它监听一个标签——包围在 while true
循环:
使用 nfc.ContactlessFrontend('usb') 作为 clf:
tag = clf.connect(rdwr=rdwr_options)
但是,在等待标记时,点击 ^C
不会使程序退出。当上面提到的行没有被 while 循环包围时,它确实可以终止程序。
我试过将它包装在一个 try
block 中并添加一个键盘中断异常,但这没有做任何事情。
到目前为止,这是我的代码:
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
方法在被 Ctrl-C 中断时返回 False
。如果 tag 为 False
,您的代码应该评估返回值并中断循环。这记录在 ContactlessFrontend.connect 末尾的返回值 下说明。
关于python - nfcpy : Can't escape a while loop constantly listening with nfcpy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44037088/