gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:30:27 24 4
gpt4 key购买 nike

为了训练,我想写一个脚本来显示最后的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com