gpt4 book ai didi

python - 是什么导致我的 Deferred 触发,除了添加回调、启动 react 器并连接端点外什么也没做?

转载 作者:太空狗 更新时间:2023-10-30 02:44:30 24 4
gpt4 key购买 nike

我正在使用 if 语句来决定是否触发 Deferred。然而,它甚至在检查运行之前就已经被解雇了。从输出来看,Deferred 似乎在运行 reactor.run() 时立即触发。难道不需要触发回调才能发生这种情况吗?

相关代码片段:

class OutpostBurrowNew(amp.AMP, Protocol):
protocol = OutpostGopher
...
def rfidTest(self):
print('Checking for tag - Deferred called: %s' % str(self.defer.called))
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
if status == MIFAREReader.MI_OK:
status,uid = self.verify_card()
cardid = '-'.join([str(x) for x in uid])
print('Card detected: %s' % str(cardid))
self.defer.callback()

def main3():
''' main3() is for testing reactor usage of RFID-card reading '''
burrow = OutpostBurrowNew('client')
burrow.protocol = OutpostGopher
burrow.connectEndpoint() # A deferred is created, set on burrow.defer
def printerCallback(proto):
# This gets passed the OutpostGopher protocol
print('main3.printerCallback() - %s ' % str(time.time()))
burrow.defer.addCallback(printerCallback)
looper = LoopingCall(burrow.rfidTest)
loopdefer = looper.start(1, now=False)
print('Deferred just created, status: %s' % str(burrow.defer.called))
reactor.run()

输出:

(env)pi@raspi ~/zenithproject/zenith $ sudo python indev/rfidread_remote.py 
Deferred just created, status: False
Gopher.connectionMade() called.
main3.printerCallback() - 1426884127.26
Checking tag - Deferred called: True
Checking tag - Deferred called: True
Checking tag - Deferred called: True
^CCtrl+C captured, ending read.

最佳答案

我发现当一个 Twisted 端点(在本例中为 TCP4ClientEndpoint)与另一个端点(此处为 TCP4ServerEndpoint)建立连接时,Deferred 由连接创建的会立即触发(即当连接时自动调用 Protocol.connectionMade())。

这是通过在需要触发 Deferred 之前不建立连接来解决的(或者,我想我可以创建另一个 Deferred 来使用),如下所示:

class OutpostBurrowNew(amp.AMP, Protocol):
protocol = OutpostGopher
#...
def rfidTest(self):
#print("Checking tag - Deferred called: %s" % str(self.defer.called))
print('Tag check')
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
if status == MIFAREReader.MI_OK:
# print "Card detected"
status,uid = self.verifyCard()
cardid = '-'.join([str(x) for x in uid])
print('Card detected: %s' % str(cardid))
#self.defer.callback()
self.connectEndpoint()

def main3():
''' main3() is for testing reactor usage of RFID-card reading '''
burrow = OutpostBurrowNew('client')
burrow.protocol = OutpostGopher
#burrow.connectEndpoint() # A deferred is created, set on burrow.defer
looper = LoopingCall(burrow.rfidTest)
loopdef = looper.start(1, now=False)
reactor.run()

结果如下:

(env)pi@raspi ~/zenithproject/zenith $ sudo python indev/rfidread_remote.py 
Tag check
Tag check
Card detected: 133-197-223-29-130
Gopher.connectionMade() called.
Tag check
Tag check

关于python - 是什么导致我的 Deferred 触发,除了添加回调、启动 react 器并连接端点外什么也没做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29175539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com