2

Can anyone tell me how to get the same program console output as variable?

For example:

print "this is simple output"
print "and this is another simple output"

ConsOutputs = some_function_to_get_those_strings_from_console()
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Why would you want to do this? There are several routes (e.g. use logging instead, roll your own `print` function, alter the `stdout`), but which is the best will depend on your aims. – jonrsharpe Sep 02 '14 at 12:42

1 Answers1

3

You can redirect the standard output to your own custom output object. You get a lot of control here, by default this will stop printing to the standard out.

import sys

class Logger():
    stdout = sys.stdout
    messages = []

    def start(self): 
        sys.stdout = self

    def stop(self): 
        sys.stdout = self.stdout

    def write(self, text): 
        self.messages.append(text)

log = Logger()

log.start()
print "sys"
log.stop()

print log.messages

If you want to log the message and print it to standard output at the same time you will have to add some more logic to the write method of the logger object.

veiset
  • 1,973
  • 16
  • 16