I'd like to know how to get the Jupyter kernel's stdout, which writes on the shell the kernel is running on, not the stdout whose output is printed to the browser. sys.stdout only gives the latter, which is, eg. <ipykernel.iostream.OutStream at 0x17d85a28880>.
1 Answer
Short answer: The kernel has only one sys.stdout: the ipykernel.stdout. Then, the input messages written in ipykernel.stdout is sent to the proper front ends.
Long answer: First a little analogy: you can picture yourself a brain that processes computation: this is the kernel. Although, the kernel, the brain, does not perform them in its own will, it needs the cognition, an interface, to receive order and to communicate the answer: this is the console.
IPython splits the REPL (Read, Evaluate, Print, Loop) in two parts. The kernel is the evaluate part, the console is handling the rest. sys.stdout is the object that writes the display. If you use ipython then you use the front end of IPython - ipython console. The same kernel can be used for another front end: the notebook. And so on. You can look into the IPython documentation for illustrations (and another version of this explanation).
So, we attach a frontend to the kernel, the kernel does not care about the detail of displaying (IPython, notebook etc...). The frontend receive messages from the kernel. (There is a format ZMQ of JSON message).
Important edit: You can read the code for ipykernel.iostdout. This is a writer for the socket exchanging messages by JSON to the frontend. To be more precise, the kernel has a sys.stdout which is only a writer for messages to be print on any frontend.
3 Comments
ipykernel.iostdout object? Then, how does the kernel print some kernel-related messages on the shell where it is running, apart from the ones on the notebook(which is on the browser). I thought the shell is the genuine stdout and, ipykernel.iostdout from sys.stdout would be just a stdout-pretending one for convenience, particularly for the communication between the kernel and the notebook as you explained.