运行 shell Python 中的内置命令

Run shell builtin command in Python

为了训练,我想写一个脚本来显示最后一个 bash/zsh 命令。

首先,我尝试用 os.systemsubprocess 来执行 history 命令。但是,如您所知,history 是一个 shell 内置函数,因此,它不会 return 任何东西。

然后,我尝试了这段代码:

shell_command = 'bash -i -c "history -r; history"' event = Popen(shell_command, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)

但它刚刚显示了上次会话的命令。我想看到的是之前的命令(我刚刚输入的) 不幸的是,我尝试了 cat ~/.bash_history 并得到了相同的结果。

有什么想法吗?

您可以使用 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)