diff --git a/src/revpi_middleware/dbus_middleware1/dbus_helper.py b/src/revpi_middleware/dbus_middleware1/dbus_helper.py index 23bcd2e..62dd766 100644 --- a/src/revpi_middleware/dbus_middleware1/dbus_helper.py +++ b/src/revpi_middleware/dbus_middleware1/dbus_helper.py @@ -41,3 +41,38 @@ def extend_interface(*args) -> str: the provided segments. """ return ".".join([REVPI_DBUS_NAME, *args]) + + +def grep(pattern, filename): + """ + Searches for lines in a file that contain a given pattern and returns them as a list. + + The function reads lines from the specified file and checks whether each line + contains the provided pattern. It returns a list of lines that match the + pattern. If the file is not found, an empty list is returned. Any other + exceptions during the file reading process are caught and logged. + + Args: + pattern (str): The substring to search for within the file's lines. + filename (str): The path to the file that will be searched. + + Returns: + list[str]: A list containing lines that include the provided pattern, with + leading and trailing spaces removed. + + Raises: + FileNotFoundError: This error is caught if the file specified is not + found. + Exception: Any unforeseen exception during file operations is caught and + logged. + """ + try: + with open(filename, "r") as file: + # Gibt alle Zeilen zurück, die das Muster enthalten + matching_lines = [line.strip() for line in file if pattern in line] + return matching_lines + except FileNotFoundError: + return [] + except Exception as e: + log.error(f"Error reading file: {e}") + return []