你可以使用tail
得到最後一行:
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)
out = Popen(["tail", "-n", "1"], stdin=event.stdout, stdout=PIPE)
output = out.communicate()
print(output[0])
或者只是把標準輸出,並獲得最後一行:
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)
print(event.communicate()[0].splitlines()[-1])
或閱讀bash_history
:
from os import path
out= check_output(["tail","-n","1",path.expanduser("~/.bash_history")])
print(out)
或者在python中打開文件,直到迭代到文件末尾:
from os import path
with open(path.expanduser("~/.bash_history")) as f:
for line in f:
pass
last = line
print(last)
你期望/希望它顯示什麼? –
如果將這些命令放在shell腳本中並運行它們會發生什麼?你得到你想要的輸出嗎? – dimo414
@EricRenouf如果我讓你感到困惑,我很抱歉。但是,我希望它顯示以前的命令,而不是在以前的bash會話中的命令 –