from io import StringIO import sys # get standard output tmp = sys.stdout my_result = StringIO() sys.stdout = my_result print('hello world') # output stored in my_result sys.stdout = tmp print(result.getvalue())