Skip to content

Instantly share code, notes, and snippets.

@basilfx
Created March 29, 2015 08:58
Show Gist options
  • Save basilfx/2ff6b2fb43d53843a10d to your computer and use it in GitHub Desktop.
Save basilfx/2ff6b2fb43d53843a10d to your computer and use it in GitHub Desktop.
Python 2/3 Autocomplete

Python 2/3 Autocomplete + history

Add autocomplete and history to your Python REPL. Saves history per interpreter/version file.

Installation

  • Create a ~/.python/ folder.
  • Move the autocomplete script in that folder.
  • Add export PYTHONSTARTUP=~/.python/autocomplete to your ~/.profile file.
  • Happy coding!

Known issues

  • Only tested with OS X
import atexit
import sys
import os
# Determine interpreter
readline = None
interpreter = ""
try:
import __pypy__
interpreter = "-pypy"
except ImportError:
__pypy__ = None
# Read the history file
histfile = os.path.join(os.environ["HOME"], ".python", "history%s%d" % (
interpreter, sys.version_info.major))
try:
import readline
atexit.register(readline.write_history_file, histfile)
readline.read_history_file(histfile)
except ImportError:
print("Module readline not available. History disabled.")
except IOError:
pass
# Tab completion
rlcompleter = None
if readline is not None:
try:
import rlcompleter
if "libedit" in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
except ImportError:
print("Module rlcompleter not available. Tab completion disabled.")
# Unset the rest
del atexit, os, sys, readline, histfile, interpreter, rlcompleter, __pypy__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment