File: readline.py

package info (click to toggle)
python-rcon 2.4.9-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 348 kB
  • sloc: python: 1,224; makefile: 42; sh: 6
file content (42 lines) | stat: -rw-r--r-- 1,164 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
"""Wrapper for readline support."""

from logging import Logger
from pathlib import Path

try:
    from readline import read_history_file, write_history_file
except ModuleNotFoundError:
    read_history_file = write_history_file = lambda _: None


__all__ = ["CommandHistory"]


HIST_FILE = Path.home() / ".rconshell_history"


class CommandHistory:
    """Context manager for the command line history."""

    def __init__(self, logger: Logger, file: Path = HIST_FILE):
        """Set the logger to use."""
        self.logger = logger
        self.file = file

    def __enter__(self):
        """Load the history file."""
        try:
            read_history_file(self.file)
        except FileNotFoundError:
            self.logger.warning("Could not find history file: %s", self.file)
        except PermissionError:
            self.logger.error("Insufficient permissions to read: %s", self.file)

        return self

    def __exit__(self, *_):
        """Write to the history file."""
        try:
            write_history_file(self.file)
        except PermissionError:
            self.logger.error("Insufficient permissions to write: %s", self.file)