python - 在 Python 中运行 shell 内置命令

标签 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)

但它刚刚显示了上次 session 的命令。我想看到的是之前的命令(我刚刚输入的) 不幸的是,我尝试了 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)

关于python - 在 Python 中运行 shell 内置命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32146111/

相关文章:

javascript - 使用 casper 登录 Facebook

python - 在 mac os 和 python 中设置 SIGKILL 处理程序时出现 OSError

node.js - 对电视的网络请求可从除 Raspberry Pi 以外的任何设备运行

Linux CLI - 光栅到矢量(追踪)

windows - 带有命令替换的 git 命令不返回任何内容

bash - 遍历 bash 中的子目录

python - 为什么 from read_data import get_minibatch() 返回 ModuleNotFoundError : No module named 'read_data'

python - 如何以字符串形式导入模块?

python - 获取整个站点 python

linux - Sh, awk : how to convert integers, 在 shell 中可见为 16 位低位/大端二进制整数的字符串?