Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get current console output in python

I want to get the current console output of my program in python. There are a lot of solutions to get the console output when running an external program, however, I couldn't find any solution for getting the console output of the current program. Am I missing something? I am looking for a solution which works under windows and linux.

For example:

print "Hello world"
output = get_console_output() # Returns "Hello World\n"

Edit: The solution should preserve the console output, so just replacing stdout won't work, as the console will be empty then

like image 451
tobspr Avatar asked Mar 05 '26 16:03

tobspr


2 Answers

If you want to access the output you need to redirect the standard output stdout somewhere. You can use StringIO for this for example:

from cStringIO import StringIO
import sys

sys.stdout = buffer = StringIO()

print "Hello World"

# get output via: buffer.getvalue()

If you rather want the output to a file you could instead redirect directly to a file:

import sys
sys.stdout = open('output.txt', 'w')
print 'Hello World'

Edit: If you want output to be appended to log (according to comment), I suggest a custom class:

import sys

class Log(object):
    def __init__(self):
        self.orgstdout = sys.stdout
        self.log = open("log.txt", "a")

    def write(self, msg):
        self.orgstdout.write(msg)
        self.log.write(msg)  

sys.stdout = Log()
print('Hello World')
like image 147
Qiau Avatar answered Mar 08 '26 06:03

Qiau


You can overwrite sys.stdout with any file-like object:

import sys
import StringIO
sys.stdout = StringIO.StringIO()

You should also think about using the logging module instead of print. Or simply write a function that stores and prints values.

like image 27
Klaus D. Avatar answered Mar 08 '26 05:03

Klaus D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!