Search code examples
pythoninputprintingoutputsystem

Python handling system output without returns


I have two programs. The functions inside the first program return some message and contains many prints. So, I import the first program functions into the second program and use the return values. However, I need the prints of the first program too. How can I get them?

FYI I cannot append print values in the return. Is there any way to get all the prints used by the program?

Example code:

First program1.py

class Test():
    def first(self,name):
        print "first print"
        print "second print"
        print "third print"
        #do some thing..
        return {"sucess":"end result"}

Second program2.py

from firstprog import Test
result = Test().first("testing")
return result + "first program prins here"

Solution

  • You can patch the sys.stdout by making it your own StringIO object.

    import StringIO
    import sys
    
    def my_function():
        print("foo")
        return 5
    
    stdout = sys.stdout
    sys.stdout = my_stdout = StringIO.StringIO()
    
    result = my_function()
    
    sys.stdout = stdout
    print(my_stdout.getvalue())  # prints foo
    print(result)  # prints 5