1

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:

enter image description here

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

3
  • That's the default appearance. But listings provides many options for customization, see tex.stackexchange.com/a/54687/5049 for an example
    – cgnieder
    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.
    – jub0bs
    Nov 30 '13 at 19:42
  • 2
    You might want to look into the minted package.
    – shyamupa
    Nov 30 '13 at 19:49
5

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,
    frame=shadowbox,
    rulesepcolor=\color{gray},
    xleftmargin=20pt,
    framexleftmargin=15pt,
    keywordstyle=\color{blue}\bf,
    commentstyle=\color{OliveGreen},
    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.

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.