[Tex/LaTex] Python code block outside of margin

listingsmarginssourcecodesyntax

I want to include some Python code to my Latex document. I have read this Tex Stackexchange question and added the following code to get syntax highlights:

\usepackage{color}
\DeclareFixedFont{\ttb}{T1}{txtt}{bx}{n}{12} % for bold
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{12}  % for normal
\definecolor{deepblue}{rgb}{0,0,0.5}
\definecolor{deepred}{rgb}{0.6,0,0}
\definecolor{deepgreen}{rgb}{0,0.5,0}

\newcommand\pythonstyle{\lstset{
    language=Python,
    basicstyle=\ttm,
    otherkeywords={self},             
    keywordstyle=\ttb\color{deepblue},
    emph={__init__},          
    emphstyle=\ttb\color{deepred},    
    stringstyle=\color{deepgreen},
    frame=tb,                         
    showstringspaces=false  
}}

\newcommand\pythonexternal[2][]{{
    \pythonstyle
    \lstinputlisting[#1]{#2}}
 }

Using the above code, the Python code in the Latex document is extremely large and it also goes far outside the right margin.

I only have a basic knowledge of Latex and don't really know how I can fix these issues.

Best Answer

I improved upon my own question by taking some bits from this SO question.

My code for Python syntax coloring and layout is now like this:

\usepackage{color}
\DeclareFixedFont{\ttb}{T1}{txtt}{bx}{n}{12} % for bold
\DeclareFixedFont{\ttm}{T1}{txtt}{m}{n}{12}  % for normal
\definecolor{deepblue}{rgb}{0,0,0.5}
\definecolor{deepred}{rgb}{0.6,0,0}
\definecolor{deepgreen}{rgb}{0,0.5,0}

% Python style for highlighting
\newcommand\pythonstyle{\lstset{
    language=Python,
    basicstyle=\footnotesize,
    otherkeywords={self},             
    keywordstyle=\footnotesize\color{deepblue},
    emph={__init__},          
    emphstyle=\footnotesize\color{deepred},    
    stringstyle=\color{deepgreen},
    frame=single,                         
    showstringspaces=false  ,
    breaklines=true,
    numbers=left,
    numberstyle=\footnotesize,
    tabsize=3,
    breakatwhitespace=false
}}

% Python environment
\lstnewenvironment{python}[1][]
{
    \pythonstyle
    \lstset{#1}
}{}

% Python external
\newcommand\pythonexternal[2][]{{
    \pythonstyle
    \lstinputlisting[#1]{#2}}
}

%Python inline
\newcommand\pythoninline[1]{{\pythonstyle\lstinline!#1!}}

All this code results in the following look:

example

So now, the Python code is smaller and stays inside the margin, solving my original problem.