[Tex/LaTex] Frame for lstinputlisting but not lstlisting

framedlistings

I'm using listings for a document which contains code examples within the TeX file and also inputed from external files. I'd like horizontal lines above and below the latter but not the former, but with my current set-up I get them for both. My preamble has

 \lstset{
         basicstyle=\footnotesize\ttfamily,
         escapechar=¢,
         language=python,
         frame=lines
 }

I know I can over-ride the frame for lstlisting with \begin{lstlisting}[frame=none] but is there a way to do it automatically without having to do this?

I've got lots and lots of listings, so I'd prefer change the preamble but not to change the main document text if possible.

Here's an example of how it works at the moment:

\documentclass{article}

\usepackage{filecontents}
\begin{filecontents*}{code.py}
for j in range(100):
    print(j)
    print(j**3)
\end{filecontents*}

\usepackage{listings}
\lstset{
         basicstyle=\footnotesize\ttfamily,
         escapechar=¢,
         language=python,
         frame=lines
 }

\begin{document}
An inline code example:
\begin{lstlisting}
for i in range(10):
    print(i**2)
\end{lstlisting}

Some code inputted from elsewhere:
\lstinputlisting{code.py}

\end{document}

As you can see, I get lines around both code listings, but I don't want them around the first one.

Best Answer

Redefine \lstinputlisting to always use frame=lines:

enter image description here

\documentclass{article}

\usepackage{filecontents}
\begin{filecontents*}{code.py}
for j in range(100):
    print(j)
    print(j**3)
\end{filecontents*}

\usepackage{listings}
\lstset{
   basicstyle=\footnotesize\ttfamily,
   escapechar=¢,
   language=python
}
\let\oldlstinputlisting\lstinputlisting
% \lstinputlisting always have frame=lines
\renewcommand{\lstinputlisting}[2][]{\oldlstinputlisting[frame=lines,#1]{#2}}

\begin{document}
An inline code example:
\begin{lstlisting}
for i in range(10):
    print(i**2)
\end{lstlisting}

Some code inputted from elsewhere:
\lstinputlisting[caption=code example]{code.py}

\end{document}
Related Question