views:

633

answers:

4

Is there any way to inject a command into a bash prompt in Linux? I am working on a command history app - like the Ctrl+R lookup but different. I am using python for this.

I will show a list of commands from history based on the user's search term - if the user presses enter, the app will execute the command and print the results. So far, so good.

If the user chooses a command and then press the right or left key, I want to insert the command into the prompt - so that the user can edit the command before executing it.

If you are on Linux, just fire up a bash console, press Ctrl+r, type cd(or something), and then press the right arrow key - the selected command will be shown at the prompt. This is the functionality I am looking for - but I want to know how to do that from within python.

+1  A: 

ncurses with its python port is a way to go, IMHO.

Mike Hordecki
+3  A: 

You can do this, but only if the shell runs as a subprocess of your Python program; you can't feed content into the stdin of your parent process. (If you could, UNIX would have a host of related security issues when folks run processes with fewer privileges than the calling shell!)

If you're familiar with how Expect allows passthrough to interactive subprocesses (with specific key sequences from the user or strings received from the child process triggering matches and sending control back to your program), the same thing can be done from Python with pexpect. Alternately, as another post mentioned, the curses module provides full control over the drawing of terminal displays -- which you'll want if this history menu is happening within the window rather than in a graphical (X11/win32) pop-up.

Charles Duffy
+3  A: 

See readline module. It implements all these features.

Sergei Stolyarov
+3  A: 

If I understand correctly, you would like history behaviour similar to that of bash in a python app. If this is what you want the GNU Readline Library is the way to go.

There is a python wrapper GNU readline interface but it runs only on Unix. readline.py is seem to be a version for Windows, but I never tried it.

Ludwig Weinzierl