簡體   English   中英

Python:獲取shell命令“ history”的輸出

[英]Python: get output of the shell command 'history'

我的最終目標是捕獲終端中執行的上一條命令。 由於〜/ .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中執行類似的命令?

為什么不直接讀取文件。 〜/ .bash_history

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM