简体   繁体   English

在Python中运行shell内置命令

[英]Run shell builtin command in Python

For training, I have idea to write a script which will display the last bash/zsh command. 为了进行培训,我想编写一个脚本来显示最后的bash / zsh命令。

First of all, I tried with os.system and subprocess to execute history command. 首先,我尝试使用os.systemsubprocess os.system执行history命令。 But, as you know, history is a shell builtin, so, it doesn't return anything. 但是,正如您所知, history是内置的shell,因此它不会返回任何内容。

Then, I tried this piece of code: 然后,我尝试了这段代码:

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

But it have just shown commands from last session. 但是它刚刚显示了上次会话的命令。 What i want to see is the previous command (which i just typed) I tried cat ~/.bash_history and have same result, unluckily. 我想看的是不幸的是,我尝试过cat ~/.bash_history的上一个命令(我刚刚键入了命令),结果却相同。

Any idea ? 任何想法 ?

You could use tail to get the last line: 您可以使用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])

Or just split the output and get the last line: 或仅拆分输出并获得最后一行:

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])

Or read bash_history : 或阅读bash_history

from os import path
out= check_output(["tail","-n","1",path.expanduser("~/.bash_history")])
print(out)

Or open the file in python and just iterate until you get to the end of the file: 或在python中打开文件并进行迭代,直到到达文件末尾:

from os import path
with open(path.expanduser("~/.bash_history")) as f:
    for line in f:
        pass
    last = line
    print(last)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM