2015-08-21 202 views
0

对于培训,我有想法编写一个脚本,它将显示最后一个bash/zsh命令。在Python中运行shell内置命令

首先,我试着用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)

但它刚刚从上届会议中所示的命令。我想看到的是前面的命令(我刚输入的) 我试过cat ~/.bash_history,结果不一样,不幸的是。

有什么想法?

+1

你期望/希望它显示什么? –

+0

如果将这些命令放在shell脚本中并运行它们会发生什么?你得到你想要的输出吗? – dimo414

+0

@EricRenouf如果我让你感到困惑,我很抱歉。但是,我希望它显示以前的命令,而不是在以前的bash会话中的命令 –

回答

2

你可以使用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) 
+0

如果我让你感到困惑,我很抱歉,但是,我只是不知道如何获得先前的命令,而不是以前的bash会话的命令。 anw,谢谢你的回答 –

+0

@TùngPun,前面的命令,来自当前shell吗? –

+0

是的。例如,运行'cat smtfile'命令后,我运行我的脚本,返回给我的脚本应该包含'cat smtfile' –