13d35cfcb64d83bd4019053045cd95b4

I've an application in twisted which, among other features, has a TCPServer for management. Telnetting to port 5005 you can give commands like stop and force. Now I need to write a simple command-line interface to it, but cannot have it working

#!/usr/bin/env python                                                                                                                                             

from twisted.internet.protocol import ClientCreator, Protocol
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
import sys

class Sender(Protocol):
    def sendCommand(self, command):
        print "invio", command
        self.transport.write(command)

    def dataReceived(self, data):
        print "DATA", data

PORT = 5005
HOST = 'localhost'

def sendCommand(command):
    def test(d):
        print "Invio ->", command
        d.sendCommand(command)
    c = ClientCreator(reactor, Sender)
    c.connectTCP(HOST, PORT).addCallback(test)

if __name__ == '__main__':
    if len(sys.argv) != 2 or sys.argv[1] not in ['stop', 'next_call', 'force']:
        sys.stderr.write('Usage: %s: {stop|next_call|force}\n' % sys.argv[0])
        sys.exit(1)
    sendCommand(sys.argv[1]+'\n')
    reactor.run()

Refactorings

No refactoring yet !

13d35cfcb64d83bd4019053045cd95b4

https://www.google.com/accounts/o8/id?id=AItOawkapZWfDKPlzk45bKWi1klRG7GdRd4leuU

July 1, 2010, July 01, 2010 07:21, permalink

No rating. Login to rate!

Line ending is wrong. Shame on me. '\r\n' works just fine!
And I should stop the reactor!

#!/usr/bin/env python                                                                                                                                             

from twisted.internet.protocol import ClientCreator, Protocol
from twisted.protocols.basic import LineReceiver
from twisted.internet import reactor
import sys

class Sender(Protocol):
    def sendCommand(self, command):
        self.transport.write(command)

    def dataReceived(self, data):
        print "Received:", data
        reactor.stop()

PORT = 5005
HOST = 'localhost'

def sendCommand(command):
    def test(d):
        d.sendCommand(command)
    c = ClientCreator(reactor, Sender)
    c.connectTCP(HOST, PORT).addCallback(test)

if __name__ == '__main__':
    if len(sys.argv) != 2 or sys.argv[1] not in ['stop', 'next_call', 'force']:
        sys.stderr.write('Usage: %s: {stop|next_call|force}\n' % sys.argv[0])
        sys.exit(1)
    sendCommand(sys.argv[1]+'\r\n')
    reactor.run()
8d60d16244ca1b6480f70cf4fd03d1c3

clonecd570

May 9, 2011, May 09, 2011 00:30, permalink

No rating. Login to rate!

Love is blind, as well as hatred.

Your refactoring





Format Copy from initial code

or Cancel