One way would be to use pythontex
package:
\documentclass{article}
\usepackage{pythontex}
\newcommand\insPython[1]{
\begin{figure}
\centering
\pyc{import os;
print (r"#1")}
\end{figure}
}
\begin{document}
\insPython{bla bla}
\end{document}
You need to run pdflatex
then pythontex
(or pythontex.exe
) and pdflatex
again.
Somehow I needed to use Python 3 syntax, but maybe because I have both Python 2 and Python 3 installed on my system.
Here is the way I like to do. Of course you can change colors, font sizes, borders and so on.
You need Pygments to use minted
.
MWE
\documentclass[11pt,a4paper]{report}
\usepackage{tcolorbox}
\tcbuselibrary{minted,breakable,xparse,skins}
\definecolor{bg}{gray}{0.95}
\DeclareTCBListing{mintedbox}{O{}m!O{}}{%
breakable=true,
listing engine=minted,
listing only,
minted language=#2,
minted style=default,
minted options={%
linenos,
gobble=0,
breaklines=true,
breakafter=,,
fontsize=\small,
numbersep=8pt,
#1},
boxsep=0pt,
left skip=0pt,
right skip=0pt,
left=25pt,
right=0pt,
top=3pt,
bottom=3pt,
arc=5pt,
leftrule=0pt,
rightrule=0pt,
bottomrule=2pt,
toprule=2pt,
colback=bg,
colframe=orange!70,
enhanced,
overlay={%
\begin{tcbclipinterior}
\fill[orange!20!white] (frame.south west) rectangle ([xshift=20pt]frame.north west);
\end{tcbclipinterior}},
#3}
\begin{document}
\begin{mintedbox}{python}
if transactions: Transaction.create_transactions() # if transactions = "true"
node.generate_emptyState() # empty state for all nodes
S.initial_events() # initiate initial events to start with
while not queue.isEmpty() and clock <= targetTime:
next_e = queue.get_next_event()
clock = next_e.time # move clock to the time of the event
Event.execute_event(next_e)
Queue.remove_event(next_e)
print results
\end{mintedbox}
\end{document}
Best Answer
As others have pointed out, this is because minted only activates
mathescape
inside comments.FWIW, the same is true for the t-vim module in ConTeXt. It is similar to the
minted
package for LaTeX, but usesvim
instead ofpygments
for syntax highlighting.t-vim
provides an option to load an arbitrary vim file before the source code is parsed. So, it is possible to change the parser on the fly. For example, to identify docstrings as comments, you can use the vim file given in this thread in the vim mailing list.which gives:
One difference in t-vim is that you need to use
\math{...}
(or\m{...}
) to enable math mode rather than$...$
. As withminted
andlistings
do not use spaces in math mode.To do something similar in
minted
, you will need to change the python parser so that it identifies docstrings as comments.