Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

command line in python with history

I'm writing program in python in which user is to work with program by command-line. I'm using raw_input to get command from user. I want to have "memory" like in bash, etc, so, if you press an arrow (up or down) on your keyboard, you get previous/next command. I know about one way to do it (simply get every char typed by user and check it), but maybe you know something better / cuter :-)

greetings

like image 992
sokoli Avatar asked Mar 14 '13 17:03

sokoli


People also ask

Where is Python command history stored?

On Windows 7, using the standard Python 3.7 command interpreter (not IPython or IDLE), the command history is stored in the file %USERPROFILE%\. python_history .

What is command line history?

Command history is a feature in many operating system shells, computer algebra programs, and other software that allows the user to recall, edit and rerun previous commands. Command line history was added to Unix in Bill Joy's C shell of 1978; Joy took inspiration from an earlier implementation in Interlisp.


1 Answers

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

Be careful though, it's possible to build python without readline so I'd suggest importing it inside a try block:

try:
    import readline
except:
    pass #readline not available
like image 132
FatalError Avatar answered Oct 07 '22 01:10

FatalError