0
import sys,re,os
from subprocess import Popen, PIPE, call


newCmd = 'diff -qr -b -B '+sys.argv[1]+' '+sys.argv[2]+' --exclude-from='+sys.argv[3]+' | grep pattern1\|pattrern2 > outputFile'

ouT,erR = Popen(newCmd, shell=True).communicate()
print ouT,erR

ouT and erR are printing None, None and the outputFile is a blank file.

When i execute the same 'newCmd' in normal shell, its executing fine

Basically, the intention here is to redirect the output of shell command into a file inside python ..Tried different approaches (using call), nothing worked out for me

user1228191
  • 681
  • 3
  • 10
  • 19
  • 1
    possible duplicate: http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python – Joe Apr 19 '15 at 11:36
  • Do you want the output to go to outputFile or to the `ouT` variable? – cdarke Apr 19 '15 at 12:18

1 Answers1

0

Unless you really need to separate stdout/stderr (according to your original post, you don't), one way to do it would be to use subprocess.check_output. It's like Popen, but captures the output and returns it as a string. After that you can manipulate the output in python (instead of using 'grep' for instance) and write the resulting string into the file of your choice.

output_as_string = subprocess.check_output('dir', shell=True)
# i'll replace all "bananas" into "apples" just for demo purposes:
manip_output = output_as_string.replace('bananas', 'apples')

with open('yourfile.txt', 'w') as f:
    f.write(manip_output)
Joe
  • 2,496
  • 1
  • 22
  • 30