对于培训,我有意写一个脚本,它将显示最后一个bash / zsh命令。
首先,我尝试使用os.system
和subprocess
来执行history
命令。但是,正如您所知,history
是内置的shell,因此,它不会返回任何内容。
然后,我尝试了这段代码:
shell_command = 'bash -i -c "history -r; history"'
event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
但它刚刚显示了上次会话的命令。我想看到的是上一个命令(我刚刚输入)
我试过cat ~/.bash_history
并且结果不一样。
有什么想法吗?
答案 0 :(得分:2)
您可以使用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)