我有一个代码正在运行并成功打印 ATR、UID 和状态,但是,程序在检测并打印 UID 后结束。如何在检测到并等待移除和插入不同的卡(或同一张卡)后重置我的代码
我尝试过使用 while 循环,但这会导致程序多次打印 ATR、UID 和状态,并且当卡被移除时,程序会因错误而终止。
from smartcard.CardRequest import CardRequest
from smartcard.Exceptions import CardRequestTimeoutException
from smartcard.CardType import AnyCardType
from smartcard import util
WAIT_FOR_SECONDS = 60
# respond to the insertion of any type of smart card
card_type = AnyCardType()
# create the request. Wait for up to x seconds for a card to be attached
request = CardRequest(timeout=WAIT_FOR_SECONDS, cardType=card_type)
# listen for the card
service = None
try:
service = request.waitforcard()
except CardRequestTimeoutException:
print("ERROR: No card detected")
exit(-1)
# when a card is attached, open a connection
conn = service.connection
conn.connect()
# get and print the ATR and UID of the card
get_uid = util.toBytes("FF CA 00 00 00")
print("ATR = {}".format(util.toHexString(conn.getATR())))
data, sw1, sw2 = conn.transmit(get_uid)
uid = util.toHexString(data)
status = util.toHexString([sw1, sw2])
print("UID = {}\tstatus = {}".format(uid, status))
它尝试过的修复(这会继续打印,当我取出卡时它会终止(已解决)):
from smartcard.CardRequest import CardRequest
from smartcard.Exceptions import CardRequestTimeoutException
from smartcard.CardType import AnyCardType
from smartcard import util
WAIT_FOR_SECONDS = 60
# respond to the insertion of any type of smart card
card_type = AnyCardType()
# create the request. Wait for up to x seconds for a card to be attached
request = CardRequest(timeout=WAIT_FOR_SECONDS, cardType=card_type)
while True:
# listen for the card
service = None
try:
service = request.waitforcard()
except CardRequestTimeoutException:
print("ERROR: No card detected")
# could add "exit(-1)" to make code terminate
# when a card is attached, open a connection
try:
conn = service.connection
conn.connect()
# get the ATR and UID of the card
get_uid = util.toBytes("FF CA 00 00 00")
data, sw1, sw2 = conn.transmit(get_uid)
uid = util.toHexString(data)
status = util.toHexString([sw1, sw2])
# print the ATR and UID of the card
print("ATR = {}".format(util.toHexString(conn.getATR())))
print("UID = {}\tstatus = {}".format(uid, status))
except:
print("no connection")
问题是我不知道如何创建一个打印一次的循环。打印 UID 后,它等待卡被移除并输入另一个卡,然后循环重置。
编辑:我设法使代码重置,但是,我不知道如何让程序打印一次而不是继续打印。有什么建议么?
我希望代码在智能卡出现后打印一次,然后当智能卡被移除时,重置并再次收听智能卡。