你可以使用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会话中的命令 –