Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

unix - Python piping output between two subprocesses

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'

The current method I tried was:

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)

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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()

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...