# How to number the listings within sections?

I use this excellent approach for inserting external Python code in my document. How to highlight Python syntax in LaTeX Listings \lstinputlistings command

\section{TEST}
\pythonexternal[caption=test, label=lst.test.py]{test.py}


But how can I number the listing in my document?

I have tried:

\uespackage{chngcntr}
\counterwithin{lstlisting}{section}


The result: "! Package chngcntr Error: lstlisting is not a counter."

• lstlisting - I have tried lstlistings, listing... nothing solved this problem... – GenXGer Jul 14 '18 at 13:35

The listings package delays the definition of the lstlisting counter until the AtBeginDocument phase. (See lines 1567 to 1576 in the file listings.sty for the complete details.) Hence, the \counterwithin{lstlisting}{section} instruction has to be wrapped in an \AtBeginDocument instruction in order to be successful.
\documentclass{article}