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

3
  • 3
    Sounds similar to stackoverflow.com/questions/1218933/… Commented Feb 4, 2012 at 8: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. Commented Feb 4, 2012 at 8:41
  • 1
    I need this to be done within the python file, not on the shell.. Commented Feb 4, 2012 at 9:02

2 Answers 2

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'
Sign up to request clarification or add additional context in comments.

1 Comment

I would add try: yield; finally:....
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.