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.
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__ .
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.
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
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__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With