You can save yourself some effort and earn yourself some "Pythonic" points with this little trick:
import sys
print('hello', file=sys.stdout)
Of course, print
already goes to sys.stdout
by default, so maybe I'm missing something. I'm not sure what's going on with the open('text', 'w')
, but it might not be necessary if you do it this way :)
In answer to your question about the variable assignment impact, when you use the =
operator on a variable, you are actually assigning it to the value in the scope dictionary (in this case globals
).
So when you import sys
, sys
gets imported in the globals
dictionary.
So globals
looks like,
{...,
'sys': <module 'sys' (built-in)>}
You can think of the module itself as a dictionary. So when you do sys.stdout=
... that's like doing globals()['sys'].__dict__['stdout'] =...
When you just import stdout
, globals
looks like:
{...,
'stdout': <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>}
Thus when you do stdout=...
you're really directly replacing that key in the dictionary:
globals()['stdout'] = ...
Hopefully that helps add a little clarity!