Python capture all printed output

8.5k views Asked by At

I am looking to write console based programs in python that can execute functions to perform generic tasks, pretty generic. Is it possible to capture everything written to the console by print calls in a function without needing to return a string, similar to how bash and the windows shell allow piping the output of a program to a text file, ie

ipconfig>ipconfig.txt

but doing this inside of a python program, where a function is called, everything that was printed to the console inside of that function is gathered as a list of strings, and then can be saved to a txt file of the users choice?

1

There are 1 answers

1
Simon Gibbons On BEST ANSWER

You can do this by setting sys.stdout to be a file of your choice

import sys

sys.stdout = open('out.dat', 'w')
print "Hello"

sys.stdout.close()

Will not display any output but will create a file called out.dat with the printed text.

Note that this doesn't need to be an actual file but could be a StringIO instance, which you can just use the getvalue method of to access everything that has been printed previously.