gpt4 book ai didi

python - 扭曲的逻辑错误

转载 作者:太空狗 更新时间:2023-10-29 20:25:16 25 4
gpt4 key购买 nike

我的扭曲程序可以运行,但现在我的一个 react 器没有将优先级传递给其他 react 器时出现问题。我希望 controlListener react 器进行一次迭代,然后将优先级传递给 printstuffs react 器。

 #Random class as proof of concept
class printStuffs(object):
print "counting "
printerCount = 0
def count(self):
self.printerCount = self.printerCount + 1
print ("the counter is at " + str(self.printerCount))

##########################################################################
## The control listneer class is designed to kill given reactor threads ##
## on demand from something once it recieves a signal it is supposed ##
## to do one ieteration then release ##
##########################################################################

class controlListener(object):
counter = 20
def count(self):
if self.counter == 0:
print "Killing Process"
reactor.stop()
else:
print self.counter, '...'
self.counter -= 1
reactor.callLater(1, self.count)

from twisted.internet import reactor

print "Printing random stuff"
reactor.callWhenRunning(printStuffs().count)

print "Intializing kill listner"
reactor.callWhenRunning(controlListener().count)
reactor.run()

print "Process killed"

这是输出

  Printing random stuff
Intializing kill listner
the counter is at 1
20 ...
19 ...
18 ...
17 ...
16 ...
15 ...
14 ...
13 ...
12 ...
11 ...
10 ...
9 ...
8 ...
7 ...
6 ...
5 ...
4 ...
3 ...
2 ...
1 ...
Killing Process
Process killed

我想让它做类似的事情

 the counter is at 1 
20 ...
the counter is at 2
the counter is at 3
19 ...

有什么想法吗?

最佳答案

您只是忘记了使用 reactor.callLater()printStuffs.count() 重新安排自己,就像 controlListener.count() 一样.

class printStuffs(object):  
printerCount = 0
def count(self):
self.printerCount = self.printerCount + 1
print ("the counter is at " + str(self.printerCount))
reactor.callLater(1, self.count)

此外,将打印语句(print "counting")直接放在类定义中而不是函数中会导致它在 python 解释器读取类定义时立即运行。这是误导性的,因为该消息说“正在计数”,但当时(还)没有真正发生任何事情。


这可能是那些看不见的错误之一。
这就是为什么对于一些重要的函数或线程,我会在我的代码中添加跟踪日志记录语句,告诉我函数何时被调用,或者线程何时开始何时结束。这对于可能因错误而中止的函数和您希望大部分时间运行的线程特别有用。

这就是您如何使此模式适应您的示例:

class printStuffs(object):
printerCount = 0
def count(self):
try:
##print "Entering printStuffs.count()."
self.printerCount = self.printerCount + 1
print ("The counter is at " + str(self.printerCount))
# Run again later.
reactor.callLater(1, self.count)
except:
# We won't run again later.
print "Error in printStuffs.count(), won't run again:", sys.exc_info()[0]
# Don't swallow the exception.
raise
finally:
##print "Leaving printStuffs.count()."

当然,这对于您的示例来说有点过分了,但您的实际代码可能更复杂。

当您的程序变得更大更复杂时,以这种方式使用日志记录可以帮助您验证程序中的基本流程是否按预期工作。

关于python - 扭曲的逻辑错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682730/

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