SoFunction
Updated on 2024-11-13

Adding Autocomplete and History to Python IDLE

Many times, when we use Python, we don't have to write a program, and for some uncomplicated tasks, I prefer to type a few lines of code in IDLE (i.e., Interactive Prompting Mode). However, there are some things that are not convenient about editing code in this mode, most notably, you can't use Tab to auto-complete, and you can't memorize the last command you typed (you can't help it, we're used to it in the Shell).
At this point, we can just use the Python startup script to solve the problem.

The procedure for starting the script is very simple, so I won't explain it much here, just give the code:

import readline
import rlcompleter
import atexit
import os
# tab autocomplete
readline.parse_and_bind(‘tab: complete')
# history file
histfile = (['HOME'], ‘.pythonhistory')
try:
readline.read_history_file(histfile)
except IOError:
pass
(readline.write_history_file, histfile)
del os, histfile, readline, rlcompleter 

Once it's done, we save it as .pythonstartup in our own directory (e.g. /home/yurii) and point the PYTHONSTARTUP variable to the address we just put it in, and we're done. The least expensive way to do this is to add a line like this to bashrc:

Copy Code The code is as follows.

export PYTHONSTARTUP=/home/yurii/.pythonstartup

This not only adds the auto-completion function of tab, but also makes it very convenient to flip to the last command you typed when restarting IDLE by using the up and down keys.