Autocomplétion dans l'interpréteur interactif Python

Je vous propose une petite astuce pour activer l'autocomplétion ainsi qu'un historique des commandes tapées dans l'interpréteur Python. Python 2.0 minimum est requis

#!/usr/bin/env python
# Add auto-completion and a stored history file of commands to your Python
# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
# bound to the Esc key by default (you can change it - see readline docs).
#
# Store the file in ~/.pystartup, and set an environment variable to point
# to it, e.g. "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
#
# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
# full path to your home directory.

import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
import os
histfile = os.path.join(os.environ["HOME"], ".pyhist")
try:
    readline.read_history_file(histfile)
except IOError:
    pass
import atexit
atexit.register(readline.write_history_file, histfile)
del histfile, readline, rlcompleter
  1. Sauvegarder le code ci dessus dans un fichier : ~/.pystartup
  2. Définissez une variable d'environnement pointant vers ce fichier dans le fichier bashrc : (~/.bashrc) :
export PYTHONSTARTUP=/home/user/.pystartup  

David

La discussion continue ailleurs

URL de rétrolien : https://davidmasclet.gisgraphy.com/index.php?trackback/11

Fil des commentaires de ce billet