Syntaxhighlighting mit Pygments und LaTeX

Hier ein Beispiel, wie man aus LaTeX-Dateien heraus a) Dateien schreibt b) diese Dateien durch einen externen Interpreter (in diesem Fall Python) ausführen lässt, c) die Ergebnisse wieder in TeX anzeigt und d) dabei das Syntax-Highlighting durch pygments erledigen lässt.

Wichtig: --shell-escape muss aktiviert sein, eine Python-Distribution (ich bevorzuge Anaconda) muss installiert sein, Python im Pfad sein.

Das Beispiel lässt sich leicht auf alle anderen Sprachen ausweiten, die im Batch-Verfahren ausführbar sind.

English: The following example shows how one can write code for external interpreters directly in LaTeX. During compilation the code is written to external files, run be the interpreter, its results stored in the corresponding .plog output file. Syntax hightlighting is done via pygments. --shell-escape must be set for the TeX-compiler!

\documentclass[12pt]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
 
\definecolor{colBack}{rgb}{1,1,0.8}
 
\usepackage{minted}
 
\setminted[python]{frame=lines, framesep=2mm, baselinestretch=1.2, bgcolor=colBack,fontsize=\footnotesize,linenos}
\setminted[text]{frame=lines, framesep=2mm, baselinestretch=1.2, bgcolor=colBack,fontsize=\footnotesize,linenos}
 
\usepackage{fancyvrb}
 
\makeatletter
\newenvironment{pycode}[1]%
  {\xdef\d@tn@me{#1}\xdef\r@ncmd{python #1.py > #1.plog}%
  \typeout{Writing file #1}\VerbatimOut{#1.py}% 
  }
  {\endVerbatimOut %
 \toks0{\immediate\write18}%
 \expandafter\toks\expandafter1\expandafter{\r@ncmd}%
 \edef\d@r@ncmd{\the\toks0{\the\toks1}}\d@r@ncmd %
 \noindent Input
 \inputminted{python}{\d@tn@me.py}%
 \noindent Output
 \inputminted{text}{\d@tn@me.plog}%
}
\makeatother
 
 
\begin{document}
 
\begin{pycode}{abc}
import pandas as pd
print(pd.__version__);
print(1+123424)
\end{pycode}
 
 
\end{document}

Uwe

Uwe Ziegenhagen likes LaTeX and Python, sometimes even combined. Do you like my content and would like to thank me for it? Consider making a small donation to my local fablab, the Dingfabrik Köln. Details on how to donate can be found here Spenden für die Dingfabrik.

More Posts - Website