2

I want to print rather than catch the output from a bash command (more closer to real-time than this post). For instance, I have a script like this:

from subprocess import Popen, PIPE, STDOUT
cmd = 'rsync --rsh=ssh -rv thisdir/ servername:folder/'
p = Popen(cmd.split() ,stdout=PIPE, stderr=STDOUT)
output = p.communicate()[0]
print output

I want the details of the file transfer from rsync printed in real time as if rsyncing from command line, rather than waiting for the process to finish to print the output.

Community
  • 1
  • 1
hatmatrix
  • 42,883
  • 45
  • 137
  • 231

2 Answers2

4

Try doing this way:

from subprocess import Popen, PIPE, STDOUT
cmd = 'rsync --rsh=ssh -rv thisdir/ servername:folder/'
p = Popen(cmd.split(), stdout=PIPE, stderr=STDOUT)
for line in p.stdout:
    print line

Note, that p.stdout has hardcoded buffer (8192 bytes), if you want to start reading file at once, try this:

for line in iter(p.stdout.readline,''):
    print line
ovgolovin
  • 13,063
  • 6
  • 47
  • 78
1
import subprocess
cmd = 'rsync --rsh=ssh -rv thisdir/ servername:folder/'
subprocess.call(cmd, shell=True)

(The shell=True paramater interprets the string by passing it to sh, allowing sh to split the string into tokens.)

Flimm
  • 136,138
  • 45
  • 251
  • 267