使用python打印bash历史记录

时间:2018-11-28 11:19:55

标签: python subprocess

我必须使用子程序包打印bash历史记录。

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

2 个答案:

答案 0 :(得分:1)

通常,您需要向shell=True调用中添加Popen参数:

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

或者手动指定要调用的外壳。

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

不幸的是,在这种特殊情况下它无济于事,因为bash在非交互式使用时历史记录为空。

一种可行的解决方案是手动阅读${HOME}/.bash_history

答案 1 :(得分:0)

工具包是正确的,读SELECT . . ., MAX(DR) OVER (PARTITION BY col1ID, col3ID) FROM (SELECT t.*, DENSE_RANK() OVER (PARTITION BY col1ID, col3ID ORDER BY Col4String) as dr FROM t ) t 可能是更好的选择:

~/.bash_history