1

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.

4

4 回答 4

3

如果我理解正确,您希望历史行为类似于 python 应用程序中的 bash。如果这是您想要的,那么GNU Readline 库就是您要走的路。

有一个 python 包装器GNU readline 接口,但它只在 Unix 上运行。 readline.py似乎是 Windows 的版本,但我从未尝试过。

于 2009-04-11T17:55:56.527 回答
3

您可以这样做,但前提是 shell 作为 Python 程序的子进程运行;您不能将内容输入父进程的标准输入。(如果可以的话,当人们以低于调用 shell 的权限运行进程时,UNIX 会出现许多相关的安全问题!)

如果您熟悉Expect如何允许传递到交互式子进程(使用来自用户的特定键序列或从子进程接收的字符串触发匹配并将控制发送回您的程序),则可以使用 Python 使用pexpect完成相同的操作。或者,正如另一篇文章所提到的,curses模块提供了对终端显示绘制的完全控制——如果这个历史菜单发生在窗口内而不是图形 (X11/win32) 弹出窗口中,您将需要它。

于 2009-02-07T16:50:09.427 回答
3

请参阅readline模块。它实现了所有这些功能。

于 2009-04-11T17:32:30.373 回答
1

恕我直言,带有python端口的ncurses是一种方法。

于 2009-02-07T16:42:45.700 回答