Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
643 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...