我的最終目標是捕獲在終端中執行的先前命令。由於〜/ .bash_history不包含來自當前終端會話的命令,因此我無法簡單地讀取該文件。Python:獲取shell命令的輸出'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中執行類似的命令嗎?
'history'不是可執行文件,它是一個shell內建。 – geoffspear
檢查[關於如何運行bash內置的問題](http://stackoverflow.com/questions/5460923/run-bash-built-in-commands-in-python) –