Reputation: 1774
The standard sys.out shows the following in python
>>> print('a')
'a'
>>> import sys; sys.out
<_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
How is this _io.TextIOWrapper
actually defined? How would one re-create that (or change it) in python?
Upvotes: 2
Views: 2169
Reputation: 24691
sys.stdout
and sys.stderr
are the paths to the standard output and error streams, respectively. They are used internally by functions such as print()
, and are 'mirrored' by sys.__stdout__
and sys.__stderr__
, which shouldn't be directly used for anything except restoring the original values. From our point of view as programmers, these may as well be hardcoded in - they're part of the initialization routine that Python does as it starts up, when the sys
module is loaded and before the program actually starts running.
You can change sys.stdout
to any other stream/file descriptor/whatever, if you want, as long as it implements the same interface (file descriptors should work, as should pipes, or even sockets if you wrap them in an appropriate custom class), and anything that would normally print to sys.stdout
(such as the built-in print()
) will start printing to that instead. Similarly with sys.stderr
. In fact, the help()
message for the sys()
module includes the following:
stdin -- standard input file object; used by input() stdout -- standard output file object; used by print() stderr -- standard error object; used for error messages By assigning other file objects (or objects that behave like files) to these, it is possible to redirect all of the interpreter's I/O.
As for the actual interface, you can find a python definition in the cpython source code here, which should suffice for your purposes. Most python installations will use that as a backup only if they can't compile the actual C definition, which you may find more difficult to understand.
Upvotes: 2