A good and simple solution is to use IDLE2HTML, an extension for IDLE.
The tool allows IDLE to save code from the editor window (or interactive shell) to a HTML file,
with colour included in the CSS format. After this, the file can be printed (as asked for) or its formatted code used with other programs such as word processors.
A reliable website currently to download the Python files and view some instructions is the Python Package Index (PyPI) - the page is https://pypi.python.org/pypi/IDLE2HTML or the pip
module, built-in to newer Python versions, can install the files for you.
An useful advantage of this method is that it gets the colour formatting from IDLE instead of taking time analysing the code and using stored colours (which many other solutions do). This means it uses the actual colour scheme and works with different IDLE themes such as "IDLE Dark". This should result in less resources and shorter code being used.
Also, the current extension (version 2.0) could probably be adapted to use a different file format when saving the data because it has quite simple code.
Some details about how it works:
Since the tool is Python code running as an extension, it has access to a special variable provided by IDLE, which contains data about the editor window. The extend.txt
file of the idlelib
Python extension (that runs the editor) describes this variable called editwin
:
An IDLE extension class is instantiated with a single argument,
`editwin', an EditorWindow instance.
It also includes some other files about extending IDLE such as "config-main.def" and "config-extensions.def". The official Python documentation has more information.
Installation instructions:
Copy IDLE2HTML.py to the "idlelib" folder of your python installation.
Append the contents of "config-extensions.txt" to your "config-extensions.def" file (also in the idlelib folder) and restart IDLE.
How to use:
Select "Save as HTML" from the "Options" menu and specify the filename in the FileDialog window. The HTML file is created immediately.
A code tweak to work in Python 3.x:
Currently, the IDLE2HTML extension (version 2.0) won't work with Python 3.x until a small change is made to the code which I found in a fixed version included with the IDLEX Python module.
Here is a file comparison, with the original on the left and the fixed IDLEX version on the right of the screenshot image.
Description: if Python version is Python 3.x, use import tkinter as Tkinter
instead of import Tkinter
and import tkinter.filedialog as tkFileDialog
instead of import tkFileDialog
. The code shown uses sys.version
from the built-in "sys" module in an if/else block to run the right code.