Skip to main content

Stdout on Google Colab Notebook in Python

How can I turn stdout to the terminal back, when use 'sys.stdout' on Google Colab Notebook in Python.
import sys
print(sys.__stdout__)
print(sys.stdout)
# <_io.TextIOWrapper name='' mode='w' encoding='UTF-8'>
# <ipykernel.iostream.OutStream object at 0x7f1042f742d0>
Those are differen. Once output to a file, the system does not turn to the original output system easily.
Recommend that first the original output is stored to a variable.
temp_stdout = sys.stdout
Finally you can change the stdout to a file.
sys.stdout = open('out.txt', 'w')
print('Output to the file.')
sys.stdout = sys.__stdout__
print('Where is output?')
sys.stdout = temp_stdout
print('Output to the terminal')

Comments