2

I'm trying to store the print output from a function of another module imported, as a string and write it into a file. However, that function does not return a string, it only prints the output. so I need something like:

import someModule
......
f.open('test.v','w')
out = storetheprintoutputasstring(someModule.main())
f.write(out)
f.close

How do I do this? Please help me out and thank you in advance

CosmicRabbitMediaInc
  • 1,165
  • 4
  • 21
  • 32
  • 3
    Sounds similar to http://stackoverflow.com/questions/1218933/can-i-redirect-the-stdout-in-python-into-some-sort-of-string-buffer – MatthewD Feb 04 '12 at 08:40
  • 2
    If you are working on a Unix based OS, simply use output redirection. `$python someModule.py > output_file.txt` If not, then you'll want to read in from stdout and write to your file. I'm operating under the assumption that you don't need to have this done dynamically. – batbrat Feb 04 '12 at 08:41
  • 1
    I need this to be done within the python file, not on the shell.. – CosmicRabbitMediaInc Feb 04 '12 at 09:02

2 Answers2

8

I think what you're asking to do is a bit of a hack, so I assume you have to do it this way.

Here is how you could redirect stdout to a file using the with statement:

import sys
from contextlib import contextmanager

@contextmanager
def redirected(stdout):
    saved_stdout = sys.stdout
    sys.stdout = open(stdout, 'w')
    yield
    sys.stdout = saved_stdout

with redirected(stdout='file.txt'):
    print 'Hello'
print 'Hello again'
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

mod1.py:

def main():
    print "BOHOO"

mod2.py:

import sys
from StringIO import StringIO
import mod1

def storetheprintoutputasstring(func):
    saved_stdout = sys.stdout
    sys.stdout = mystdout = StringIO()
    func()   # Call function
    sys.stdout = saved_stdout
    return mystdout.getvalue()

f = open('test.v','w')
out = storetheprintoutputasstring(mod1.main)
f.write(out)
f.close()

Run python mod2.py.

test.v contains:

BOHOO
mzjn
  • 48,958
  • 13
  • 128
  • 248