在Python中运行shell内置命令

在Python中运行shell内置命令,python,linux,bash,shell,built-in,Python,Linux,Bash,Shell,Built In,为了进行培训,我想编写一个脚本,显示最后一个bash/zsh命令 首先,我尝试使用os.system和subprocess执行history命令。但是,正如您所知,history是一个内置的shell,因此它不会返回任何内容 然后,我尝试了这段代码: shell_命令='bash-i-c“history-r;history”' event=Popen(shell_命令,shell=True,stdin=PIPE,stdout=PIPE,stderr=stdout) 但它刚刚显示了上一个会话中的命

为了进行培训,我想编写一个脚本,显示最后一个bash/zsh命令

首先,我尝试使用
os.system
subprocess
执行
history
命令。但是,正如您所知,
history
是一个内置的shell,因此它不会返回任何内容

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

shell_命令='bash-i-c“history-r;history”'
event=Popen(shell_命令,shell=True,stdin=PIPE,stdout=PIPE,stderr=stdout)

但它刚刚显示了上一个会话中的命令。我想看到的是上一个命令(我刚刚键入) 我尝试了
cat~/.bash\u 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])
或者只需拆分输出并获取最后一行:

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\u历史记录

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脚本中并运行它们会发生什么?你得到你想要的输出了吗?@EricRenouf如果我让你感到困惑,我很抱歉。但是,我希望它显示上一个命令,而不是上一个bash中的命令session@dimo414我以前试过,但也不起作用:(因此,您的问题是历史记录的内容不是您期望的内容?Bash不会在每个命令之后写入.Bash_历史记录,因此您可能只是得到了正确的结果,但不是您想要的结果。您可以在启动python之前试着运行
history-a
,以将该会话写入文件(如果您想要的话)请看,如果我让您感到困惑,我非常抱歉,但是,我只是不知道如何获取上一个命令,而不是上一个bash会话中的命令。嗯,谢谢您的回答。是的。例如,在运行
cat smtfile
命令之后,我运行了我的脚本,它返回给我的内容应该包含
cat smtfile
确定,那么这是一个完全不同的脚本或者,如果是供您自己使用,您可以将export
PROMPT\u COMMAND=“${PROMPT\u COMMAND:+$PROMPT\u COMMAND$'\n'}历史-a;历史-c;历史-r”
添加到.bashrc文件中,如下所述