Python capture all printed output
Asked Answered
M

1

13

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?

Masterpiece answered 19/6, 2015 at 16:8 Comment(1)
Sure. Run the Python script from the shell, and use the shell to redirect output as usual.Charwoman
A
16

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.

Astrology answered 19/6, 2015 at 16:11 Comment(1)
@Simon Gibbons , Is it also possible to also output the same on the console along with parallely writing in the "out.dat" file?Stace

© 2022 - 2024 — McMap. All rights reserved.