Python:获取shell命令'history'的输出

时间:2013-08-19 17:27:27

标签: python linux shell ubuntu terminal

我的最终目标是捕获终端中执行的上一个命令。由于〜/ .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()

这与我正在寻找的非常接近,但它也不包括当前终端会话的历史记录,因为它是作为子进程启动的。有没有办法在当前shell中执行类似的命令?

1 个答案:

答案 0 :(得分:4)

为什么不直接阅读该文件。 的〜/ .bash_history的

for history in open('/home/user/.bash_history'):
    print(history, end='')