The problem is simple. I copied an example from a python book about output redirection and firstly sys.stdout
is changed to a file object and then is restored to sys.__stdout__
.
However the restoration part doesn't seem to work because the output later in the code doesn't get displayed at all anywhere.
I found out the issue which i'll explain with this shell code sample:
>>> import sys
>>> sys.stdout
<idlelib.run.StdOutputFile object at 0x00000191D0BCFB50>
>>> sys.__stdout__
>>> print(sys.__stdout__)
None
>>>
So: why is sys.__stdout__
equal to None
by default?
EDIT: i know about the context manager in contextlib explained in this issue but i still would like to know why this happens.
CodePudding user response:
It's likely that you're using an OS environment where sys.stdout
is not normally set with an initial value. Two relevant portions of the documentation are quoted below (bolded emphasis mine):
From the IDLE documentation:
By default, IDLE runs user code in a separate OS process rather than in the user interface process that runs the shell and editor. In the execution process, it replaces
sys.stdin
,sys.stdout
, andsys.stderr
with objects that get input from and send output to the Shell window. The original values stored insys.__stdin__
,sys.__stdout__
, andsys.__stderr__
are not touched, but may beNone
.
From the sys
module documentation:
Under some conditions
stdin
,stdout
andstderr
as well as the original values__stdin__
,__stdout__
and__stderr__
can beNone
. It is usually the case for Windows GUI apps that aren’t connected to a console and Python apps started with pythonw.
Under these conditions, IDLE is setting a value for sys.stdout
when the initial values for sys.stdout
and sys.__stdout__
were None
.
If this is problematic for the environment you're using, you can always save the initial value of sys.stdout
and restore it later.
CodePudding user response:
According to the docs:
Under some conditions stdin, stdout and stderr as well as the original values
__stdin__
,__stdout__
and__stderr__
can be None. It is usually the case for Windows GUI apps that aren’t connected to a console and Python apps started with pythonw.
You're using IDLE, which does not bind __stdout__
as it's a GUI app. It overrides sys.stdout
to the IDLE default stdout
stream.