kramer65
kramer65

Reputation: 53873

Improved IDE'ish Python command line including code completion?

For writing Python I currently use the excellent PyCharm IDE. I love the way it has code completion so that you often only need to type the first 2 letters and then hit enter.

For easy testing I am of course also often on the command line. The only thing is that I miss the convenient features of the IDE on the command line. Why is there no code completion on the command line? And when I fire up a new Python interactive interpreter, why doesn't it remember commands I inserted earlier (like for example sqlite3 does)?

So I searched around, but I can't find anything like it, or I'm simply not searching for the right words.

So my question; does anybody know of an improved and more convenient version of the Python interactive command line interpreter? All tips are welcome!

Upvotes: 1

Views: 798

Answers (1)

Lukas Graf
Lukas Graf

Reputation: 32600

bpython is one of the many choices for alternative interactive Python interpreters that sports both of the features you mentioned (tab completion and persistent readline history).

bpython screenshot

Another very commonly used one would by IPython, though I personally don't like it very much (just a personal preference, many people are very fond of it).

Last but not least you can also enable those features for the standard Python interpreter:

Create a file ~/.pythonrc in your home directory containing this script:

try:
    import readline
except ImportError:
    print "Module readline not available."
else:
    import rlcompleter
    readline.parse_and_bind("tab: complete")

This will try to import the readline module, and bind its default completion function to the tab key. In order to execute this script every time you start a Python interpreter, set the environment variable PYTHONSTARTUP to contain the path to this script. How you do this depends on your operating system - on Linux you could do it in your ~/.bashrc for example:

export PYTHONSTARTUP="/home/lukas/.pythonrc"

(The file doesn't need to be called .pythonrc or even be in your home directory - all that matters is that it's the same path you set in PYTHONSTARTUP)

  • Persistent history: See the .pythonrc file in Marius Gedminas's dotfiles. The concept is the same as above: You add the code that saves and loads the history to your ~/.pythonrc, and configure the PYTHONSTARTUP environment variable to contain the path to that script, so it gets executed every time you start a Python interpreter.

His script already contains the tab completion part. So since you want both, you could save his script called python to ~/.python and add the contents of his bashrc.python to your ~/.bashrc.

Upvotes: 4

Related Questions