使用 python 打印 bash 历史记录 [英] Print bash history using python
本文介绍了使用 python 打印 bash 历史记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须使用子进程包打印 bash 历史记录.
I have to print bash history using subprocess package.
import subprocess
co = subprocess.Popen(['history'], stdout = subprocess.PIPE)
History = co.stdout.read()
print("----------History----------" + "\n" + History)
但他们提示错误
Traceback (most recent call last):
File "test.py", line 4, in <module>
co = subprocess.Popen(['history'], stdout = subprocess.PIPE)
File "/usr/lib/python2.7/subprocess.py", line 394, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1047, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
推荐答案
通常,您需要在 Popen
调用中添加 shell=True
参数:
Normally, you would need to add shell=True
argument to your Popen
call:
co = subprocess.Popen(['history'], shell=True, stdout = subprocess.PIPE)
或者手动指定要调用的shell.
Or to manually specify the shell you want to call.
co = subprocess.Popen(['/bin/bash', '-c', 'history'], stdout = subprocess.PIPE)
不幸的是,在这种特殊情况下它无济于事,因为 bash
在非交互式使用时具有空历史记录.
Unfortunately, in this particular case it won't help, because bash
has empty history when used non-interactively.
一个可行的解决方案是手动读取 ${HOME}/.bash_history
.
A working solution would be to read ${HOME}/.bash_history
manually.
这篇关于使用 python 打印 bash 历史记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文