gpt4 book ai didi

python - 如何使用 python 结构发送流

转载 作者:行者123 更新时间:2023-12-02 14:09:58 25 4
gpt4 key购买 nike

我需要通过网络将程序的标准输出流发送到在另一台主机上运行的另一个程序的标准输入。

这可以使用 ssh 轻松完成:

program 1 | ssh host 'program 2'

使用 subprocess 调用它很简单:
subprocess.call("program 1 | ssh host 'program 2'", shell=True)

但是,由于我需要在远程主机上运行许多其他命令,所以我使用 fabric .

用织物发送文件很容易,但我找不到任何关于发送流的文档。我知道fabric 使用paramiko ssh 库,所以我可以 use it's channel但似乎没有从结构访问 channel 的文档。

最佳答案

我最终挖掘了织物源代码( fabric.operations._execute )并得出了这个:

from fabric.state import default_channel
import subprocess

def remote_pipe(local_command, remote_command, buf_size=1024):
'''executes a local command and a remove command (with fabric), and
sends the local's stdout to the remote's stdin.
based on fabric.operations._execute'''
local_p= subprocess.Popen(local_command, shell=True, stdout=subprocess.PIPE)
channel= default_channel() #fabric function
channel.set_combine_stderr(True)
channel.exec_command( remote_command )
read_bytes= local_p.stdout.read(buf_size)
while read_bytes:
channel.sendall(read_bytes)
read_bytes= local_p.stdout.read(buf_size)
local_ret= local_p.wait()
channel.shutdown_write()
received= channel.recv(640*1024) #ought to be enough for everyone
remote_ret= channel.recv_exit_status()
if local_ret!=0 or remote_ret!=0:
raise Exception("remote_pipe failed: "+received)

关于python - 如何使用 python 结构发送流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19596920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com