Python: get output of the shell command 'history'

故事扮演 提交于 2019-12-29 00:50:07

问题


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()

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?


回答1:


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

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


来源:https://stackoverflow.com/questions/18319605/python-get-output-of-the-shell-command-history

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!