feat(dbus): Add grep function to search for patterns in a file
The new `grep` function reads a specified file and returns lines containing a given pattern. It handles file not found errors and logs unexpected exceptions, improving resilience in file operations.
This commit is contained in:
@@ -41,3 +41,38 @@ def extend_interface(*args) -> str:
|
|||||||
the provided segments.
|
the provided segments.
|
||||||
"""
|
"""
|
||||||
return ".".join([REVPI_DBUS_NAME, *args])
|
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 []
|
||||||
|
|||||||
Reference in New Issue
Block a user