简体   繁体   中英

How to pipe python socket to a stdin/stdout

I need to write an app to contact to a server. After sending a few messages it should allow the user to interact with the server by sending command and receive result.

How should I pipe my current socket so that the user can interact with the server without the need of reading input and writing output from/to stdin/stdout ?

You mean like using netcat?

cat initial_command_file - | nc host:port

the answer is, something needs to read and write. In the sample shell script above, cat reads from two sources in sequence, and writes to a single pipe; nc reads from that pipe and writes to a socket, but also reads from the socket and writes to its stdout .

So there will always be some reading and writing going on ... however, you can structure your code so that doesn't intrude into the comms logic.

For example, you use itertools.chain to create an input iterator that behaves similarly to cat , so your TCP-facing code can take a single input iterable:

def netcat(input, output, remote):
    """trivial example for 1:1 request-response protocol"""
    for request in input:
        remote.write(request)
        response = remote.read()
        output.write(response)

handshake = ['connect', 'initial', 'handshake', 'stuff']
cat = itertools.chain(handshake, sys.stdin)

server = ('localhost', 9000)
netcat(cat, sys.stdout, socket.create_connection(server))

You probably want something like pexpect . Basically you'd create a spawn object that initates the connection (eg via ssh ) then use that object's expect() and sendline() methods to issue the commands you want to send at the prompts. Then you can use the interact() method to turn control over to the user.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM