How to physically print python code in color from IDLE?

user1063287 picture user1063287 · May 30, 2013 · Viewed 20.2k times · Source

I have searched for an answer to this but the related solutions seem to concern 'print'ing in the interpreter.

I am wondering if it is possible to print (physically on paper) python code in color from IDLE?

I have gone to: File > Print Window in IDLE and it seems to just print out a black and white version without prompting whether to print in color etc.

Edit:

It seems like this might not be available so the option is to copy code to a text editor like SciTE and print from there - quite like the default IDLE syntax highlighting though.

Answer

alexis picture alexis · Nov 28, 2013

IDLE can't do it, but you can do it in an indirect way: Use LaTeX to format your script with the IDLE colors.

The listings package supports IDLE-like colorizing for python, but it's pretty well hidden: You must know to include a "preference file" that is mentioned in the listings manual, but without a description of its features. The following almost-minimal example will turn your script myscript.py into color PDF in the IDLE colors.

\documentclass{article}

\usepackage{listings}
\input{listings-python.prf}  % defines the python-idle-code style
\usepackage{textcomp} % Needed for straight quotes                               

\lstset{
 basicstyle=\normalsize\ttfamily, % size of the fonts for the code               
 language={Python},style={python-idle-code},
 showstringspaces=false,
 tabsize=4,
 upquote=true,   % Requires textcomp                                             
}

\oddsidemargin=-0.5cm
\textwidth=7in  % This just fits 80 characters at 10pt                           

\begin{document}
\lstinputlisting{myscript.py}
\end{document}

You could also include code snippets in a real LaTeX document.

Availability: You'll need at least listings version 1.5b (2013/08/26). Users of Texlive 2013 must download it from CTAN (e.g. with the command line texlive manager, tlmgr). It is part of TexLive 2016.

Unfortunately there still seems to be a problem with the CTAN version: The preferences file listings-python.prf is in the documentation folder for the package, not in tex/latex/listings where TeX can find it. You'll need to move it manually for the inclusion to work.