Print bash history using python

狂风中的少年 提交于 2021-02-10 16:18:55

问题


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)

but they prompt an error

 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

回答1:


Normally, you would need to add shell=True argument to your Popen call:

co = subprocess.Popen(['history'], shell=True, stdout = subprocess.PIPE)

Or to manually specify the shell you want to call.

co = subprocess.Popen(['/bin/bash', '-c', 'history'], stdout = subprocess.PIPE)

Unfortunately, in this particular case it won't help, because bash has empty history when used non-interactively.

A working solution would be to read ${HOME}/.bash_history manually.




回答2:


Kit is correct, reading ~/.bash_history may be a better option:

from os.path import join, expanduser

with open(join(expanduser('~'), '.bash_history'), 'r') as f:
    for line in f:
        print(line)


来源:https://stackoverflow.com/questions/53518255/print-bash-history-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!