Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sys.stdout not reassigning to sys.__stdout__

I'm pretty new to Python so I am still just learning the language. One of the things I came across was reassigning sys.stdout to change the default output of print. So I wrote this as a test:

import sys
sys.stdout = open('log.txt','a')
print('hey')
sys.stdout.close()
sys.stdout = sys.__stdout__
print('hi')

'Hey' is written to the file, but 'hi' shows up nowhere. However, this works as expected, and 'hey' is written to the file, and 'hi' is printed to the console output:

import sys
sys.__stdout__ = sys.stdout
sys.stdout = open(r'C:\Users\Vincent\Documents\Python\log.txt','a')
print('hey')
sys.stdout.close()
sys.stdout = sys.__stdout__
print('hi')

In short its a small problem that doesnt really matter too much, I am just wondering if there's a discernible reason why its not working the way it should. I have tried this on Windows 7 Home Premium with IDLE and pyscripter on v3.2.3 and my portable python v3.2.1.

like image 279
Vince Avatar asked Oct 04 '12 01:10

Vince


People also ask

What is SYS __ stdout __?

In IDLE, sys. __stdout__ is the program's original standard output - which goes nowhere, since it's not a console application. In other words, IDLE itself has already replaced sys. stdout with something else (its own console window), so you're taking two steps backwards by replacing your own stdout with __stdout__ .

What does Sys stdout do in Python?

stdout. A built-in file object that is analogous to the interpreter's standard output stream in Python. stdout is used to display output directly to the screen console.


2 Answers

I would try this workaround (not using sys.__stdout__ at all because your environment could have made both sys.stdout and sys.__stdout__ distinct):

old_stdout = sys.stdout
sys.stdout = open('log.txt','a')
print('hey')
sys.stdout.close()
sys.stdout = old_stdout

backuping the reference of sys.stdout seems the safest way to do it. Worked in another slightly different case: stdout redirect from Jupyter notebook is landing in the terminal

like image 56
Jean-François Fabre Avatar answered Oct 13 '22 01:10

Jean-François Fabre


In IDLE, sys.__stdout__ is the program's original standard output - which goes nowhere, since it's not a console application. In other words, IDLE itself has already replaced sys.stdout with something else (its own console window), so you're taking two steps backwards by replacing your own stdout with __stdout__.

like image 23
jasonharper Avatar answered Oct 13 '22 01:10

jasonharper