Python:获取shell命令"history"的输出 [英] Python: get output of the shell command 'history'

查看:293
本文介绍了Python:获取shell命令"history"的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My end goal is capture the previous command executed in the terminal. Since ~/.bash_history doesn't include commands from the current terminal session, I can't simply read that file.

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

From another thread, I found this script:

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中执行类似的命令?

That's pretty close to what I'm looking for, but it also will not include the history from the current terminal session since it's started as a subprocess. Is there any way to execute a similar command in the current shell?

推荐答案

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

why don't you read the file directly. ~/.bash_history

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

这篇关于Python:获取shell命令"history"的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆