Python:获取shell命令“ history”的输出

Mad*_*May 4 python linux shell terminal ubuntu

我的最终目标是捕获终端中执行的上一条命令。由于〜/ .bash_history不包含当前终端会话中的命令,因此我不能简单地读取该文件。

在另一个线程中,我找到了以下脚本:

from subprocess import Popen, PIPE, STDOUT
shell_command = 'bash -i -c "history -r; history"'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, 
    stderr=STDOUT)

output = event.communicate()
Run Code Online (Sandbox Code Playgroud)

这与我要查找的内容非常接近,但是由于它是作为子进程启动的,因此它也不包括当前终端会话的历史记录。有什么办法可以在当前shell中执行类似的命令?

edi*_*len 6

为什么不直接读取文件。 〜/ .bash_history

for history in open('/home/user/.bash_history'):
    print(history, end='')
Run Code Online (Sandbox Code Playgroud)

  • 这是默认行为,但您可以编写一个函数,让 shell 在提示输入新命令之前将前一个命令附加到历史文件中。 (2认同)