Search code examples
jupyter-notebookcustomizationjupyternbconvert

Hide stderr blocks when exporting notebooks


I have a custom template for exporting from my Jupyter notebook to LaTeX.

((*- extends 'article.tplx' -*))

% Disable input cells
((* block input_group *))
((* endblock input_group *))

This works fine, but sometimes the Python code in the notebook produces warnings and errors that are helpful in the notebook but not in the export. For instance, in one notebook there is this block:

  {
   "cell_type": "code",
   "execution_count": 106,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\me\\Anaconda3\\lib\\site-packages\\ipykernel_launcher.py:3: FutureWarning: currently extract(expand=None) means expand=False (return Index/Series/DataFrame) but in a future version of pandas this will be changed to expand=True (return DataFrame)\n",
      "  This is separate from the ipykernel package so we can avoid doing imports until\n"
     ]
    }
   ],
   "source": [
    "# Some Python code using Pandas\n",
    "df = d.join(df.mycol.str.extract((?P<foo>\\d)')\n",
    ")"
   ]
  }

I'd like to exclude such errors when I export. I tried adding the following lines to my template:

% Hide Stderr output
((* block stream_stderr *))
((* endblock stream_stderr *))

However, I still see the corresponding error appear in the LaTeX output. What am I doing wrong?


Solution

  • I found myself struggling with the same problem and came up with a fix. Put this in your template file:

    ((* block stream *))
    ((*- if output.name == 'stderr' -*))
    ((*- else -*))
        \begin{Verbatim}[commandchars=\\\{\}]
    ((( output.text | escape_latex | ansi2latex )))
        \end{Verbatim}
    ((*- endif -*))
    ((* endblock stream *))