Key binding to interactively execute commands from Python interpreter history in order?

泪湿孤枕 提交于 2019-12-06 10:48:42

I often test Python modules as I develop them by running a Python interactive prompt in a terminal, importing my new module and testing out the functionality.

Stop using this pattern and start writing your test code in a file and your life will be much easier.

  • No matter what, running that file will be less trouble.

  • If you make the checks automatic rather than reading the results, it will be quicker and less error-prone to check your code.

  • You can save that file when you're done and run it whenever you change your code or environment.

  • You can perform metrics on the tests, like making sure you don't have parts of your code you didn't test.

Are you familiar with the unittest module?

Answering my own question, after some discussion on the python-ideas list: despite contradictory information in some readline documentation it seems that the operate-and-get-next function is in fact defined as a bash extension to readline, not by core readline.

So that's why Ctrl-o neither behaves as hoped by default when importing the readline module in a Python interpreter session, nor when attempting to manually force this binding: the function doesn't exist in the readline library to be bound.

A Google search reveals https://bugs.launchpad.net/ipython/+bug/382638, on which the GNU readline maintainer gives reasons for not adding this functionality to core readline and says that it should be implemented by the calling application. He also says "its implementation is not complicated", although it's not obvious to me how (or whether it's even possible) to do this as a pure Python extension to the readline module behaviour.

So no, this is not possible at the moment, unless the operate-and-get-next function from bash is explicitly implemented in the Python readline module or in the interpreter itself.

This isn't exactly an answer to your question, but if that is your development style you might want to look at DreamPie. It is a GUI wrapper for the Python terminal that provides various handy shortcuts. One of these is the ability to drag-select across the interpreter display and copy only the code (not the output). You can then paste this code in and run it again. I find this handy for the type of workflow you describe.

Your best bet will be to check that project : http://ipython.org

This is an example with a history search with Ctrl+R :

EDIT If you are running debian or derivated :

sudo apt-get install ipython
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!