【问题标题】:Python: get output of the shell command 'history'Python:获取 shell 命令“历史”的输出
【发布时间】:2013-08-21 14:13:13
【问题描述】:

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

【问题讨论】:

标签: python linux shell ubuntu terminal


【解决方案1】:

你为什么不直接阅读文件。 ~/.bash_history

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

【讨论】:

  • 因为我的最终目标是捕获在终端中执行的上一个命令,而 ~/.bash_history 不包括来自当前终端会话的命令。
  • 我应该在原始问题中更清楚地说明这一点。不过,感谢您的建议。
  • 这是默认行为,但您可以编写一个函数,让 shell 在提示输入新命令之前将前一个命令附加到历史文件中。
猜你喜欢
  • 2013-05-12
  • 2018-07-29
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-21
  • 2014-06-02
  • 2013-09-01
相关资源
最近更新 更多