[英]How to join the stdout of two subprocesses and pipe to stdin of new subprocess in python
[英]How to pipe python socket to a stdin/stdout
我需要编写一个与服务器联系的应用程序。 发送一些消息后,它应该允许用户通过发送命令与服务器进行交互并接收结果。
我应该如何通过管道传输当前套接字,以便用户可以与服务器交互,而无需从stdin / stdout读取输入或向stdin / stdout写入输出?
您是说喜欢使用netcat?
cat initial_command_file - | nc host:port
答案是, 有些东西需要读写。 在上面的示例Shell脚本中, cat
依次从两个源读取数据,并写入单个管道。 nc
从该管道读取并写入套接字,但也从套接字读取并写入其stdout
。
因此, 总会有一些读写过程。但是,您可以构造代码,以免干扰comms逻辑。
例如,您使用itertools.chain创建一个行为类似于cat
的输入迭代器,因此面向TCP的代码可以采用单个可迭代输入:
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.