.. _captureoutputrst: ================================= Capture standard output and error ================================= .. only:: html **Links:** :download:`notebook `, :downloadlink:`html `, :download:`PDF `, :download:`python `, :downloadlink:`slides `, :githublink:`GitHub|_doc/notebooks/capture_output.ipynb|*` 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 `__. .. code:: ipython3 from jyquickhelper import add_notebook_menu add_notebook_menu() .. contents:: :local: .. code:: ipython3 from cpyquickhelper.io import capture_output Python Capture with Python print -------------------------------- .. code:: ipython3 def python_print(): print("one line") print("two lines") res, out, err = capture_output(python_print, lang="py") type(out), out .. parsed-literal:: (str, 'one line\ntwo lines\n') C Capture with C print ---------------------- .. code:: ipython3 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 .. parsed-literal:: (bytes, b'o\x00n\x00e\x00 \x00l\x00i\x00n\x00e\x00t\x00w\x00o\x00 \x00l\x00i\x00n\x00e\x00s\x00') Python capture with C print --------------------------- .. code:: ipython3 res, out, err = capture_output(c_print, lang="py") type(out), out .. parsed-literal:: (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. .. code:: ipython3 res, out, err = capture_output(python_print, lang="c") type(out), out .. parsed-literal:: one line two lines .. parsed-literal:: (NoneType, None)