And now for a bit of Python programming. Brought to you by a slow, procrastinating afternoon in the office.
I hate doing this:
>>> exit Use exit() or Ctrl-Z plus Return to exit >>> exit() C:\>
Why can’t Python exit when I just type exit? Because typing anything in the shell without parenthesis ‘()’ will only display the variable value’s string repr. Can we fix this? Yes.
Create a sitecustomize.py module and put it somewhere in your Python import path (in my Windows box, for example, I saved it in C:\Python25\Lib\sitecustomize.py) with this code:
import sys
import __builtin__
def setrealquit():
"Redefine builtins 'quit' and 'exit' to actually exit when entered in the shell"
class RealQuitter(object):
def __repr__(self):
self()
def __call__(self, code=None):
try:
sys.stdin.close()
except:
pass
raise SystemExit(code)
__builtin__.quit = RealQuitter()
__builtin__.exit = RealQuitter()
def main():
setrealquit()
main()
The sitecustomize module will be imported every time the python shell is launched. This will basically replace the builtin quit and exit objects with our own ‘quitter’ that simply exits when it’s __repr__ method is called. You can override any builtins here, if you want (but remember, with great power comes great responsibility)
