How to highlight Python syntax in LaTeX Listings \lstinputlistings command
Good approach is defining new environments for programming language. Minimal setup can be around this:
\documentclass[a4paper,12pt]{article}
\usepackage[utf8]{inputenc}
% Default fixed font does not support bold face
\DeclareFixedFont{\ttb}{T1}{txtt}{bx}{n}{12} % for bold
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{12} % for normal
% Custom colors
\usepackage{color}
\definecolor{deepblue}{rgb}{0,0,0.5}
\definecolor{deepred}{rgb}{0.6,0,0}
\definecolor{deepgreen}{rgb}{0,0.5,0}
\usepackage{listings}
% Python style for highlighting
\newcommand\pythonstyle{\lstset{
language=Python,
basicstyle=\ttm,
morekeywords={self}, % Add keywords here
keywordstyle=\ttb\color{deepblue},
emph={MyClass,__init__}, % Custom highlighting
emphstyle=\ttb\color{deepred}, % Custom highlighting style
stringstyle=\color{deepgreen},
frame=tb, % Any extra options here
showstringspaces=false
}}
% Python environment
\lstnewenvironment{python}[1][]
{
\pythonstyle
\lstset{#1}
}
{}
% Python for external files
\newcommand\pythonexternal[2][]{{
\pythonstyle
\lstinputlisting[#1]{#2}}}
% Python for inline
\newcommand\pythoninline[1]{{\pythonstyle\lstinline!#1!}}
\begin{document}
\section{``In-text'' listing highlighting}
\begin{python}
class MyClass(Yourclass):
def __init__(self, my, yours):
bla = '5 1 2 3 4'
print bla
\end{python}
\section{External listing highlighting}
\pythonexternal{demo.py}
\section{Inline highlighting}
Definition \pythoninline{class MyClass} means \dots
\end{document}
Output:
I found this python package pythonhighlight on Github
Define it like this \usepackage{pythonhighlight}
and use it like this:
\begin{python}
def f(x):
return x
\end{python}
I'd consider running your code through pygments to generate the latex, probably using the minted package. You can get some details here https://stackoverflow.com/questions/1966425/source-code-highlighting-in-latex#1985330 .