M
M
malikan2015-03-24 16:38:14
Python
malikan, 2015-03-24 16:38:14

Telnet client in python: how to implement command completion in the console by tab?

Hello everyone,

Actually, at the moment I have an example:

# telnet program example
import socket, select, string, sys
 
#main function
if __name__ == "__main__":
     
    if(len(sys.argv) < 3) :
        print 'Usage : python telnet.py hostname port'
        sys.exit()
     
    host = sys.argv[1]
    port = int(sys.argv[2])
     
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(2)
     
    # connect to remote host
    try :
        s.connect((host, port))
    except :
        print 'Unable to connect'
        sys.exit()
     
    print 'Connected to remote host'
     
    while 1:
        socket_list = [sys.stdin, s]
         
        # Get the list sockets which are readable
        read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
         
        for sock in read_sockets:
            #incoming message from remote server
            if sock == s:
                data = sock.recv(4096)
                if not data :
                    print 'Connection closed'
                    sys.exit()
                else :
                    #print data
                    sys.stdout.write(data)
             
            #user entered a message
            else :
                msg = sys.stdin.readline()
                s.send(msg)


The example works, BUT it is not convenient to use such a client, there is not enough auto-completion on pressing tab. (bash completion, as far as I understand)

Tried to send sys.stdin.read(1) instead of sys.stdin.readline(), didn't help.

How to make it so that when you press tab, the line would either be automatically filled in or the possible options would be displayed?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
un1t, 2015-03-24
@malikan

If I understand correctly what you need

import readline

texts = ['hello', 'world', 'readline']

def completer(text, state):
    options = [x for x in texts if x.startswith(text)]
    try:
        return options[state]
    except IndexError:
        return None

readline.set_completer(completer)
readline.parse_and_bind("tab: complete")

while 1:
    a = raw_input("> ")
    print "You entered", a

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question