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

2024-04-26 14:54:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我的最终目标是捕获在终端中执行的前一个命令。由于~/.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中执行类似的命令?在


Tags: 文件from命令脚本bashevent终端stdout