【问题标题】:Print bash history using python使用 python 打印 bash 历史记录
【发布时间】:2019-04-30 06:58:28
【问题描述】:

我必须使用 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

【问题讨论】:

标签: python subprocess


【解决方案1】:

Kit 是正确的,阅读 ~/.bash_history 可能是更好的选择:

from os.path import join, expanduser

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

【讨论】:

    【解决方案2】:

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

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

    或者手动指定要调用的shell。

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

    不幸的是,在这种特殊情况下它没有帮助,因为bash 在非交互式使用时具有空历史记录。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-01
      • 2012-07-18
      相关资源
      最近更新 更多