marco
marco

Reputation: 1140

How do I find the location of the Python stdout file object?

In Python I know that the standard output stream is available as the stdout file object in the built-in sys module but I'm confused: first, I'm not able to locate the sys module in the way I do with any other module (modulename.__file__); secondond, I don't know how to locate the stdout file objects.

Upvotes: 0

Views: 606

Answers (1)

cdarke
cdarke

Reputation: 44364

stdout is defined in the sys module. Assuming you are using the C implementation, download the source code (3.6) and look in Python/sysmodule.c. However, stdout itself is assigned from PyId_stdout which is defined in Python/pylifecycle.c in the function initstdio:

/* Set sys.stdout */
fd = fileno(stdout);
std = create_stdio(iomod, fd, 1, "<stdout>", encoding, errors);
if (std == NULL)
    goto error;
PySys_SetObject("__stdout__", std);
_PySys_SetObjectId(&PyId_stdout, std);
Py_DECREF(std);

As you can see, it is derived from the stdio C runtime library. Also, __stdout__ is created at the same time, and this is meant to be a fall-back to recover stdout if you reassign it.

The function create_stdio in the same source file also contains further details, like buffering, newlines, and encoding.

Upvotes: 1

Related Questions