views:

82

answers:

3

So I would like to grab stdout from a subprocess and then write the output to a file using python.

The problem I'm having is the stdout from the subprocess loses the formatting, it contains \n's where there are newlines. I would like to write the output to a file with formatting intact, meaning instead of one line containg \n's, the file contains newlines where there are \n's.

Here is my existing code:

import os, subprocess
from cStringIO import StringIO

proc = subprocess.Popen('foo.exe', shell=True, stdout=subprocess.PIPE,)

stdout_value = proc.communicate()[0]

f=open('fooOut.txt', 'w')
f.write(str(repr(stdout_value)))
f.close()

Current File Text: abbbb\nabbbb\naaaaab

What I would like:

abbbb

bbbb

aaaaab

+2  A: 

Don't call repr(), ie. just call

f.write(stdout_value)
mhawke
+1  A: 

Why repr? That turns a object into its representation, which for strings means converting things like chr(10) (newline) into '\n'.

ephemient
A: 

The repr (which doubles up the "escapes", i.e. backslash characters) is what's causing you to "lose formatting" -- why are you doing that at all? And btw the str call is totally redundant (innocuous, but totally useless -- why have it there?!).

Alex Martelli