Add data_logging/src/data_logging/cli.py
This commit is contained in:
parent
58790fbfd1
commit
88010939cc
1 changed files with 74 additions and 0 deletions
74
data_logging/src/data_logging/cli.py
Normal file
74
data_logging/src/data_logging/cli.py
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
from data_logging import core
|
||||
from data_logging.core import LogEntry
|
||||
|
||||
|
||||
def _load_json_data(input_path: Path) -> List[LogEntry]:
|
||||
"""Lädt LogEntry-Daten aus einer JSON-Datei und validiert sie."""
|
||||
if not input_path.exists():
|
||||
raise FileNotFoundError(f"Eingabedatei nicht gefunden: {input_path}")
|
||||
|
||||
with input_path.open("r", encoding="utf-8") as f:
|
||||
raw_data = json.load(f)
|
||||
|
||||
if not isinstance(raw_data, list):
|
||||
raise ValueError("Erwartete JSON-Liste von Objekten.")
|
||||
|
||||
data: List[LogEntry] = []
|
||||
for item in raw_data:
|
||||
if not isinstance(item, dict):
|
||||
raise ValueError("Eintrag im JSON muss ein Objekt sein.")
|
||||
try:
|
||||
entry = LogEntry(
|
||||
timestamp=item.get("timestamp"),
|
||||
value=item.get("value"),
|
||||
status=item.get("status"),
|
||||
)
|
||||
except Exception as e:
|
||||
raise ValueError(f"Ungültiger LogEntry: {e}") from e
|
||||
data.append(entry)
|
||||
return data
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
"""CLI-Einstiegspunkt: Liest Argumente, lädt JSON-Daten und ruft log_data auf."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Protokolliert Δt<0-Datenereignisse in eine CSV-Ausgabedatei."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--input",
|
||||
required=True,
|
||||
help="Pfad zur JSON-Datei mit den zu protokollierenden Daten.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--output",
|
||||
required=True,
|
||||
help="Pfad zur Ausgabe-CSV-Datei.",
|
||||
)
|
||||
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
input_path = Path(args.input).expanduser().resolve()
|
||||
output_path = Path(args.output).expanduser().resolve()
|
||||
|
||||
try:
|
||||
data = _load_json_data(input_path)
|
||||
success = core.log_data(data, str(output_path))
|
||||
if success:
|
||||
print(f"Logging erfolgreich: {output_path}")
|
||||
return 0
|
||||
else:
|
||||
print(f"Fehler beim Logging: {output_path}", file=sys.stderr)
|
||||
return 1
|
||||
except Exception as exc:
|
||||
print(f"Fehler: {exc}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Loading…
Reference in a new issue