Question

I'm trying to edit the Keyboard IO example http://twistedmatrix.com/documents/current/core/examples/stdin.py so that I can type command while a realtime plot is happens and change what is plotted. I have the following simple code.

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()

Why doesn't lineReceived get called when I add the plotting code?

Était-ce utile?

La solution

The simplest issue is that your LineReceiver doesn't define a delimiter ivar, which could be fixed with:

from os import linesep

class Echo(basic.LineReceiver):
    delimiter = linesep

N.B. As posted, this is a pretty bizarre use of Twisted, in that it's adding complexity but not buying you anything. I understand that it may be a sketch, but you may want to rethink either using Twisted, or using threads in this manner in a Twisted application. You may also want to look into using Twisted's GTK2 reactor to get the event loop to integrate more naturally with Matplotlib's.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top