"""to use this for modifying behavior of the Python command line, put this in your $HOME/.bash_profile or equivalent: PYTHONSTARTUP=$HOME/.pythonrc.py also make a symlink to Python as 'pysh': ln -s /usr/bin/python ~/bin/pysh to reconstruct a script from the history: cp ~/.pyhistory newscript.py edit it to keep the lines you want, and also put at the beginning: #!/path/to/pysh from user import * to run the script: pysh newscript.py """ import os, sys, readline, atexit histfile = os.path.join(os.environ['HOME'], '.pyhistory') if os.path.split(sys.executable)[-1] == 'pysh': from glob import glob sys.ps1 = '$ ' sys.ps2 = '> ' DATASTACK = [] def sysstacker(value = None): index = readline.get_current_history_length() item = readline.get_history_item(index) readline.replace_history_item(index - 1, 'qpush(%s)' % item) qpush(value) print >>sys.stderr, DATASTACK sys.displayhook = sysstacker def systrapper(exctype, value, traceback): index = readline.get_current_history_length() item = readline.get_history_item(index) command = item.split() fullpath = which(command[0]) if fullpath: if os.path.isdir(fullpath) and len(command) == 1: readline.replace_history_item(index - 1, 'os.chdir(%s)' % repr(item)) os.chdir(fullpath) print >>sys.stderr, 'current working directory now: %s' % os.getcwd() sysstacker() else: command[0] = fullpath readline.replace_history_item(index - 1, 'piperun(%s)' % repr(command)) result = piperun(command) sysstacker(result) sys.exc_clear() else: sys.__excepthook__(exctype, value, traceback) sys.excepthook = systrapper # file operations def ls(arg = '*'): return glob(arg) def which(command): for path in os.getenv('PATH', '').split(':'): fullpath = os.path.join(path, command) if os.path.exists(fullpath): return fullpath # stack operations def push(arg): DATASTACK.append(arg) def qpush(arg): if arg is not None: push(arg) if isinstance(__builtins__, dict): # a dict when run as a script __builtins__['_'] = arg else: # it's a module __builtins__._ = arg def pop(arg = -1): return DATASTACK.pop(arg) def drop(arg = -1): DATASTACK.pop(arg) def swap(): DATASTACK[-2], DATASTACK[-1] = DATASTACK[-1], DATASTACK[-2] # uncategorized def piperun(command): pipe = os.popen(' '.join(command)) result = map(str.rstrip, pipe.readlines()) pipe.close() return result else: import inspect try: readline.read_history_file(histfile) except IOError: pass atexit.register(readline.write_history_file, histfile) if os.path.split(sys.executable)[-1] != 'pysh': del os, sys, readline del histfile, atexit