在Python中运行shell builtin命令

时间:2015-08-21 17:27:24

标签: python linux bash shell built-in

对于培训,我有意写一个脚本,它将显示最后一个bash / zsh命令。

首先,我尝试使用os.systemsubprocess来执行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并且结果不一样。

有什么想法吗?

1 个答案:

答案 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)