tobspr
tobspr

Reputation: 8376

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

Upvotes: 3

Views: 15950

Answers (2)

Klaus D.
Klaus D.

Reputation: 14369

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.

Upvotes: 2

Qiau
Qiau

Reputation: 6175

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')

Upvotes: 3

Related Questions