3

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

3
  • Why do you need to do this, what are you trying to achieve? You might wish to checkout StringIO in the standard library. Commented Jul 15, 2015 at 6:39
  • Not sure I understand your question: the console doesn't "generate output" it prints your output, so if you want your output save it in a string and only then print it. Or maybe I'm misunderstanding your question ? Commented Jul 15, 2015 at 6:39
  • I have a lot of print statements, and "save it in a string" would require me to change every print statement Commented Jul 15, 2015 at 6:58

2 Answers 2

3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

Is it possible to have the output redirected to a file while still outputing to the console?
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.