我正在尝试编辑键盘IO示例http://twistedmatrix.com/documents/current/core/examples/stdin.py,以便在实时绘图发生时键入命令并更改绘制的内容。我有以下简单的代码。
import random, pylab, threading, signal, time
from twisted.internet import stdio
from twisted.protocols import basic
from twisted.internet import reactor
# Start interactive mode
pylab.ion()
# Initialize lock semaphore
lock = threading.Lock()
line, = pylab.plot([], [])
class Echo(basic.LineReceiver):
def connectionMade(self):
self.transport.write('>>> ')
def lineReceived(self, line):
# This doesn't seem to execute.
self.sendLine('Echo: ' + line)
self.transport.write('>>> ')
def Update():
# Thread for updating plot
while True:
lock.acquire()
pylab.draw()
lock.release()
time.sleep(0.2)
def AddData():
# Thread for adding data
while True:
lock.acquire()
x = -1.0 + 2.0 * random.random()
y = -1.0 + 2.0 * random.random()
pylab.plot(x, y, '+g')
lock.release()
time.sleep(0.5)
def main():
stdio.StandardIO(Echo())
reactor.callInThread(AddData)
reactor.callInThread(Update)
reactor.run()
if __name__ == '__main__':
main()
为什么在添加绘图代码时不会调用lineReceived
?
答案 0 :(得分:2)
最简单的问题是您的LineReceiver没有定义分隔符ivar,可以通过以下方式修复:
from os import linesep
class Echo(basic.LineReceiver):
delimiter = linesep
N.B。据发布,这是一个非常奇怪的使用Twisted,因为它增加了复杂性,但没有给你买任何东西。我知道它可能是草图,但您可能想要重新考虑使用Twisted,或者在Twisted应用程序中以这种方式使用线程。您可能还想研究使用Twisted的GTK2反应器来使事件循环更自然地与Matplotlib集成。