Command line in python with history

I am writing a python program in which the user must work with the program on the command line. I use raw_input to get a command from a user. I want to have a β€œmemory”, for example, in bash, etc. Therefore, if you press the arrow (up or down) on the keyboard, you get the previous / next command. I know of one way to do this (just get every char typed by the user and check it out), but maybe you know something better / cuter :-)

Hello

+6
source share
2 answers

If I understand what you want, you can achieve this by simply importing the readline module. This will change the behavior of raw_input() , so that it will be more like an interactive python shell in terms of history and line editing.

Be careful, but it is possible to build python without readline , so I would suggest importing it inside a try block:

 try: import readline except: pass #readline not available 
+11
source

The built-in readline module provides this functionality.

+3
source

All Articles