Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python capture all printed output

Tags:

python

piping

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?

like image 633
BruceJohnJennerLawso Avatar asked Jun 19 '15 16:06

BruceJohnJennerLawso


1 Answers

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.

like image 196
Simon Gibbons Avatar answered Sep 29 '22 08:09

Simon Gibbons