From 37c54019ad0424e0555530092e63483b8d5cc211 Mon Sep 17 00:00:00 2001 From: Mark Joshwel Date: Mon, 4 Sep 2023 16:20:02 +0000 Subject: [PATCH] s+: add reading from stdin support (#22) --- surplus/surplus.py | 28 +++++++++++++++++++++++----- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/surplus/surplus.py b/surplus/surplus.py index e2db26c..6fd4c98 100644 --- a/surplus/surplus.py +++ b/surplus/surplus.py @@ -33,7 +33,7 @@ from argparse import ArgumentParser from collections import OrderedDict from datetime import datetime, timedelta, timezone from enum import Enum -from sys import stderr, stdout +from sys import stderr, stdout, stdin from typing import ( Any, Callable, @@ -544,10 +544,12 @@ class Behaviour(NamedTuple): dict. keys found in SHAREABLE_TEXT_LINE_*_KEYS used to access address details are placed top-level in the dict, exceptions are handled by the caller. see the playground notebook for example output - stderr: TextIO = stderr + stderr: TextIO = sys.stderr TextIO-like object representing a writeable file. defaults to sys.stderr - stdout: TextIO = stdout + stdout: TextIO = sys.stdout TextIO-like object representing a writeable file. defaults to sys.stdout + stderr: TextIO = sys.stdin + TextIO-like object representing a readable file. defaults to sts.stdin debug: bool = False whether to print debug information to stderr version_header: bool = False @@ -561,6 +563,7 @@ class Behaviour(NamedTuple): reverser: Callable[[Latlong], dict[str, Any]] = default_reverser stderr: TextIO = stderr stdout: TextIO = stdout + stdin: TextIO = stdin debug: bool = False version_header: bool = False convert_to_type: ConversionResultTypeEnum = ConversionResultTypeEnum.SHAREABLE_TEXT @@ -774,7 +777,8 @@ def handle_args() -> Behaviour: "full-length Plus Code (6PH58QMF+FX), " "shortened Plus Code/'local code' (8QMF+FX Singapore), " "latlong (1.3336875, 103.7749375), " - "or string query (e.g., 'Wisma Atria')" + "string query (e.g., 'Wisma Atria'), " + "or '-' to read from stdin" ), nargs="*", ) @@ -805,8 +809,22 @@ def handle_args() -> Behaviour: ) args = parser.parse_args() + + query: str | list[str] = "" + + if args.query == ["-"]: + stdin_query: list[str] = [] + + for line in stdin: + stdin_query.append(line.strip()) + + query = "\n".join(stdin_query) + + else: + query: list[str] = args.query + behaviour = Behaviour( - query=args.query, + query=query, geocoder=default_geocoder, reverser=default_reverser, stderr=stderr,