Listing package only outputs black colored source code even though the language parameter is specified

The problem is pretty much in the title.

With this code:

\documentclass{report}
\usepackage{listings}
\begin{document}
\lstset{language=Python}
\begin{lstlisting}
def some_function(parameter):
a_random_number = parameter - 10
print "some random string" + str(a_random_number)

if __name__ == '__main__'
print 'Hello Latex Listings package'
some_function(20)
\end{lstlisting}
\end{document}


I am getting no color whatsoever, just some bolded keywords:

Any idea why this might be and how to fix it? Thank you.

• That's the default appearance. But listings provides many options for customization, see tex.stackexchange.com/a/54687/5049 for an example Nov 30 '13 at 19:41
• That's the default style for Python, as defined in lstdrvrs.dtx (a file that ships with the listings package). You can override aspects of that style (colour, etc.) by passing new values to keys such as keywordstyle, commentstyle and stringstyle. See the documentation. Nov 30 '13 at 19:42
• You might want to look into the minted package. Nov 30 '13 at 19:49

As others have correctly mentioned in the comments, you are using default behavior. To customize it, you can do something like this

\documentclass[12pt]{article}
\usepackage{geometry}
\usepackage{listings}
\usepackage{color}
\usepackage[usenames,dvipsnames,svgnames,table]{xcolor}
\geometry{a4paper}

\begin{document}

This is a sample file:

\lstset{
language=python,
tabsize=3,
%frame=lines,
caption=Test,
label=code:sample,
rulesepcolor=\color{gray},
xleftmargin=20pt,
framexleftmargin=15pt,
keywordstyle=\color{blue}\bf,
stringstyle=\color{red},
numbers=left,
numberstyle=\tiny,
numbersep=5pt,
breaklines=true,
showstringspaces=false,
basicstyle=\footnotesize,
emph={str},emphstyle={\color{magenta}}}
%\lstinputlisting{simple.py}
\begin{lstlisting}
def some_function(parameter):
a_random_number = parameter - 10
print "some random string" + str(a_random_number)
# And a random comment!
if __name__ == '__main__'
print 'Hello Latex Listings package'
some_function(20)
\end{lstlisting}

\end{document}


You can add your python script either by using \begin{lstlisting} or saving it in an external file and then later adding it by \lstinputlisting{simple.py}. I personally prefer external files to keep the source cleaner. Moreover, you can add extra keywords as I have done for str function.