## Saturday, September 13

### Python syntax highlighting in LaTeX

LaTeX provides a listings package to typeset code. The standard output is great for black-and-white printouts, but not for beamer presentations, where a more dynamic color scheme would be suitable. Having recently worked on slides with Python code, I have prepared a file that you can include to get nice colourful code that looks good on a presentation:

My code is based on a snippet found on Ubuntu forums. I added some more keywords and tweaked the color scheme to correspond to the one that IDLE uses (that color scheme is not ideal, but my audience uses IDLE for coding and I wanted some consistency).

To use the package, copy the file to the same folder as your document and include it in the header:

\include{pythonlisting}


Then, to render code, use python sections:

\begin{python}
def foo():
print "bar"
\end{python}


Note that if you want to use this in a beamer frame, you will have to mark the frame that contains Python code as fragile, like this:

\begin{frame}[fragile]{Some Python code}

\begin{python}
def foo():
print "bar"
\end{python}

\end{frame}


Edgar Marca said...

Hi thanks for this code, it didn't work in my computer there is a problem with orange color. I have to add \definecolor{orange}{rgb}{1,0.5,0} and now it works.

Helder Silva said...

Great improvement!
I was reading the listings manual. Do you know how to activate the lstinput for your new definitions?

The purpose is to use:

\lstinputlisting{file.py}

Thanks!

Gintautas Miliauskas said...

Sorry, I'm not sure what to do about lstinputlisting. I took a quick stab, but without results, and I do not have the time to look closer into this right now. It's definitely possible though, documentation should help.

David Kofoed Wind said...

How could I apply a background color to the code box?

Maarten Bosmans said...

\lstinputlisting[language=python]{file.py}

seems to work

Thomas Lechauve said...

Hi !
Thanks a lot for your snippet,
very simple and very useful =)

Olivier Verdier said...
This comment has been removed by the author.
Olivier Verdier said...

I've published a similar package on github.

Anonymous said...

It's very useful, thanks
Is there a way to change the fontsize?