两个子进程之间的 Python 管道输出 [英] Python piping output between two subprocesses

查看:36
本文介绍了两个子进程之间的 Python 管道输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些通过 SSH DD 块设备的代码,我想用子进程来做到这一点,以便我可以在传输过程中监视 DD 的状态(用 SIGUSR1 杀死 dd 进程以获得它的当前状态,并使用选择读取).

I'm working on some code that will DD a block device over SSH, and I'm wanting to do this with subprocess so that I can monitor the status of DD during the transfer (killing the dd process with SIGUSR1 to get its current state, and reading that using selects).

我试图实现的命令是这样的:

The command that I'm trying to implement would be something like this:

dd if=/dev/sda | ssh root@example.com 'dd of=/dev/sda'

我目前尝试的方法是:

dd_process = subprocess.Popen(['dd','if=/dev/sda'],0,None,None,subprocess.PIPE, subprocess.PIPE)  
ssh_process = subprocess.Popen(['ssh','root@example.com','dd of=/dev/sda'],0,None,dd_process.stdout)

但是,当我运行它时,SSH 进程会在 10-40 秒后失效.
是我在这里完全迟钝,还是没有办法在这样的子进程之间进行管道传输?

However when I run this, the SSH process becomes defunct after 10-40 seconds.
Am I being completely obtuse here, or is there no way to pipe between subprocesses like this?

原来我的真实代码中没有主机名.这是做事的正确方式.

Turns out my real code didn't have the hostname in it. This is the correct way to do things.

推荐答案

from subprocess import Popen, PIPE
dd_process = Popen(['dd', 'if=/dev/sda'], stdout=PIPE)
ssh_process = Popen(['ssh', 'root@example.com', 'dd','of=/dev/sda'],stdin=dd_process.stdout, stdout=PIPE)
dd_process.stdout.close() # enable write error in dd if ssh dies
out, err = ssh_process.communicate()

这是将第一个进程输出管道传输到第二个进程的方法.(注意 ssh_process 中的 stdin)

This is way to PIPE the first process output to the second. (notice stdin in the ssh_process)

这篇关于两个子进程之间的 Python 管道输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆