简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM