Capture standard output and error

Links: notebook, html, PDF, python, slides, slides(2), GitHub

Python standard output is different from C standard output. When Python embeds a C library which prints something on the standard output, it is difficult to catch it from Python.

See also print and cleaning and PySys_WriteStdout.

from jyquickhelper import add_notebook_menu
from import capture_output

Python Capture with Python print

def python_print():
    print("one line")
    print("two lines")

out, err = capture_output(python_print, lang="py")
type(out), out
(str, 'one linentwo linesn')

C Capture with C print

from import cprint

def c_print():
    cprint("one line")
    cprint("two lines")

out, err = capture_output(c_print, lang="c")
type(out), out
 b'ox00nx00ex00 x00lx00ix00nx00ex00tx00wx00ox00 x00lx00ix00nx00ex00sx00')

Python capture with C print

out, err = capture_output(c_print, lang="py")
type(out), out
(str, '')

C capture with Python print

On Windows, the behavior of this code is different in a standalone program probably because jupyter catches the output on his side too.

out, err = capture_output(python_print, lang="c")
type(out), out
one line
two lines
(NoneType, None)