Search code examples
pythoncommand-linetwisted

Twisted lineReceived not getting called


I encountered a strange behavior when i was building a command line interface in python. Here is the striped down version of the code that can reproduce the issue.

from twisted.internet import reactor, stdio
from twisted.protocols import basic

class CommandLine(basic.LineReceiver):
    def __init__(self):
        self.linebuf = ''
        self.setLineMode()

    # why lineReceived  doesn't work?
    # def lineReceived(self, data):
    def dataReceived(self, data):
        print 'data received ' + ' '.join([str(ord(c)) for c in data ])
        print data


if __name__=='__main__':
    stdio.StandardIO(CommandLine())
    reactor.run()

The code above works as intended, out put in the form of "data received 108 115 115 10" is printed everytime a line is entered. Here is a sample output using dataReceived:

$ python cmdline.py
hello
data received 104 101 108 108 111 10
hello

^[[A
data received 27 91 65 10

However nothing gets printed out except the echo of the command line itself when I use lineReceived instead of dataReceived in the code above. Example output using lineReceived:

$ python cmdline.py
hello
^[[A

According the the documentation on lineReceived, the lineReceived function gets invoked when a line is received with the LineReceiver in line mode.

For now I am using dataReceived to make it work. But I would like to find out why lineReceived is not working as intended. Any hint, suggestions, advice would be very much appreciated!

Regards.


Solution

  • The reason is line delimiter constant which is set to r'\r\n' by default (MS Windows delimiter). Try to set it to '\n' (Linux and Mac OS) instead:

    class CommandLine(basic.LineReceiver):
        delimiter = '\n'