1

In the python interpreter we can use

readline.parse_and_bind('tab: complete')

to enable tab completion

Is it possible to bind arbitrary keys to our own functions?
I'd like to bind CTRL+E and CTRL+SHIFT+E to edit_history() and edit_history(True) respectively, where edit_history() is my own function defined in .pythonrc

def edit_history(fork=False):
    import readline
    timeStamp = time.strftime("%Y%m%d-%H%M%S")
    tmpFile = '/tmp/pyHistory.%s' % timeStamp
    readline.write_history_file(tmpFile)
    if not fork:
        os.system('gvim -f %s' % tmpFile)
        readline.clear_history()
        readline.read_history_file(tmpFile)
        os.unlink(tmpFile)
    else:
        os.system('gvim %s' % tmpFile)

Any pointers would be greatly appreciated

Thanks,
Dado

2
  • You should look at enhanced interpreters like iPython, it has a lot of interesting %magic. Commented Jul 27, 2012 at 1:48
  • Thanks for the suggestion Paulo, but I can't get used to iPython. Commented Jul 27, 2012 at 23:03

1 Answer 1

0

Yes... kind of. After defining your edit_history function, you can map a key to the sequence "edit_history()\n". Pressing that key would simulate typing "edit_history" followed by the Enter key.

Sign up to request clarification or add additional context in comments.

Ah, I tried that without ()\n, since the binding for complete doesn't include that. But I'm not sure how to specify keys. Do you have an example for F2 or CTRL+E? Thanks!
I managed to get it to work with readline.parse_and_bind('C-e: "edit_history()\n"') Couldn't combine Meta or Shift with that. I might need a completely separate binding. Thank you chepner for pointing me in the right direction.

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.