make python quit like a normal person

Let’s add quit and exit command support to the Python interactive interpreter. We’ll ignore all the arguments for and against. It’s just something we want.

problem

You’ve seen this before:

mackenzie:~ eweaver$ python
Python 2.5 (r25:51908, Feb 25 2007, 06:35:16)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for
more information.
>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'
>>> 

I’ll avoid editorializing, except to note:

>>> help()
Welcome to Python 2.5!  This is the online help utility.
To quit this help utility and return to the interpreter,
just type "quit".
help> quit
You are now leaving help and returning to the Python
interpreter.
>>> quit
'Use Ctrl-D (i.e. EOF) to exit.'
>>>

Hrm.

solution

Rubyists may find this very beautiful. First, in ~/.bash_profile:

export PYTHONSTARTUP=~/.pythonrc

Now, in ~/.pythonrc:

class Quit:
  def __repr__(self):
    import sys
    sys.exit()
exit = quit = Quit()
del Quit

Source your ~/.bash_profile or restart your shell. Try it out:

mackenzie:~ eweaver$ python2.5
Python 2.5 (r25:51908, Feb 25 2007, 06:35:16)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin
Type "help", "copyright", "credits" or "license" for
more information.
>>> quit
mackenzie:~ eweaver$ 

Hax!

three thoughts

A Ruby version:

quit = Object.new
def quit.inspect
  exit
end

I don’t know how to define eigenmethods in Python. Can someone fill me in? They were talking about borgs.

The Python solution is gleaned from this bug report. Contrary to what arigo says, I haven’t noticed any problems with displaying the builtins dict; dir() returns strings anyway. The issue is that you can’t do the rough equivalent of (method :quit).inspect.

an aside

I added an all articles view to Snax to make it easier to find old posts. Also the category pages use the new concise view.