Capture standard output and error¶
Links: notebook
, html, PDF
, python
, slides, 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
add_notebook_menu()
from cpyquickhelper.io import capture_output
Python Capture with Python print¶
def python_print():
print("one line")
print("two lines")
res, out, err = capture_output(python_print, lang="py")
type(out), out
(str, 'one linentwo linesn')
C Capture with C print¶
from cpyquickhelper.io.stdchelper import cprint
def c_print():
cprint("one line")
cprint("two lines")
res, out, err = capture_output(c_print, lang="c")
type(out), out
(bytes, b'ox00nx00ex00 x00lx00ix00nx00ex00tx00wx00ox00 x00lx00ix00nx00ex00sx00')
Python capture with C print¶
res, 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.
res, out, err = capture_output(python_print, lang="c")
type(out), out
one line
two lines
(NoneType, None)