Jupyter notebook does not show C++ output (cout)

Question:

I am using a Jupyter Notebook as python interface to a C++ code. If I launch the same python code with

$ python mycode.py

I can see in the Terminal all the “std::cout” statements of the C++ code, but if I execute the Jupyter Notebook block all the “cout” are not displayed.

Do you know if and how I can see the standard output stream on Jupyter Notebooks?

Thanks!

Asked By: Alberto

||

Answers:

Yes, it is a known issue. When writing Python, most objects write the the sys.stdout/sys.stderr object, provides hooks to intercept. Most compiles library don’t bother with trying to write to sys.stdin/sys.stdout, they just open the file descriptor and write to it, and you can’t intercept that. Most of the time its something that could be fix in the underlying library, but not a lot of people bother to bug-report it.

You’ll see your c++ output in the terminal where you started your notebooks. There are ideas on how to “fix” that, but it’s non-trivial.

Note, you can reproduce by directly writing the filedescriptor 1, “blah” will appear on the terminal where the notebook was started:

import os
os.write(1, 'blahn'.encode())

My Terminal:

[I 12:13:51.703 LabApp] Adapting to protocol v5.1 for kernel 5cf9f732-5a0e-417d-8b66-bc50d3cbbe80
blah
[I 12:15:51.633 LabApp] Saving file at /Untilted1.ipynb
Answered By: Matt

If you run your program with subprocess.check_output() you can get the C++ output to be displayed in the jupyter notebook.

example:

a = subprocess.check_output("./your_program")
print(a)
Answered By: Manjari S

You can use the wurlitzer package to capture C-level stdout / stderr and redirect it to IPython.

For example, include the following code blocks in your Jupyter notebook:

%load_ext Cython
%load_ext wurlitzer
%%cython
from libc.stdio cimport printf
def test():
    printf('abc')
test()
# prints "abc"
Answered By: Jayen
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.