2013-08-19 98 views
2

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

+0

'history'不是可執行文件,它是一個shell內建。 – geoffspear

+3

檢查[關於如何運行bash內置的問題](http://stackoverflow.com/questions/5460923/run-bash-built-in-commands-in-python) –

回答

4

爲什麼不直接讀取文件。 〜/ .bash_history的

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

因爲我的最終目標是捕獲以前命令在終端中執行,並且〜/ .bash_history不包括來自當前終端會話的命令。 –

+0

我應該在原始問題中說得更清楚。不過謝謝你的建議。 –

+0

這是默認行爲,但您可以編寫一個函數,讓shell在提示新命令之前將以前的命令追加到歷史文件中。 –