From aff4f1e9e2d613436af73a29299256a207655216 Mon Sep 17 00:00:00 2001 From: Tim Savage Date: Thu, 12 Mar 2020 11:22:45 +1100 Subject: [PATCH] Bugfix/1077 decode called on str fetching platformio stacktrace (#991) * Remove decode from str result, add type annotations --- esphome/platformio_api.py | 6 ++++-- esphome/util.py | 20 +++++++++++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/esphome/platformio_api.py b/esphome/platformio_api.py index 29bfe7d2e6..4866119902 100644 --- a/esphome/platformio_api.py +++ b/esphome/platformio_api.py @@ -1,4 +1,6 @@ import json +from typing import Union + import logging import os import re @@ -62,7 +64,7 @@ FILTER_PLATFORMIO_LINES = [ ] -def run_platformio_cli(*args, **kwargs): +def run_platformio_cli(*args, **kwargs) -> Union[str, int]: os.environ["PLATFORMIO_FORCE_COLOR"] = "true" os.environ["PLATFORMIO_BUILD_DIR"] = os.path.abspath(CORE.relative_pioenvs_path()) os.environ["PLATFORMIO_LIBDEPS_DIR"] = os.path.abspath(CORE.relative_piolibdeps_path()) @@ -80,7 +82,7 @@ def run_platformio_cli(*args, **kwargs): *cmd, **kwargs) -def run_platformio_cli_run(config, verbose, *args, **kwargs): +def run_platformio_cli_run(config, verbose, *args, **kwargs) -> Union[str, int]: command = ['run', '-d', CORE.build_path] if verbose: command += ['-v'] diff --git a/esphome/util.py b/esphome/util.py index 10c8d4e581..de6736096c 100644 --- a/esphome/util.py +++ b/esphome/util.py @@ -1,3 +1,5 @@ +from typing import Union + import collections import io import logging @@ -151,7 +153,21 @@ class RedirectText: return True -def run_external_command(func, *cmd, **kwargs): +def run_external_command(func, *cmd, + capture_stdout: bool = False, + filter_lines: str = None) -> Union[int, str]: + """ + Run a function from an external package that acts like a main method. + + Temporarily replaces stdin/stderr/stdout, sys.argv and sys.exit handler during the run. + + :param func: Function to execute + :param cmd: Command to run as (eg first element of sys.argv) + :param capture_stdout: Capture text from stdout and return that. + :param filter_lines: Regular expression used to filter captured output. + :return: str if `capture_stdout` is set else int exit code. + + """ def mock_exit(return_code): raise SystemExit(return_code) @@ -160,13 +176,11 @@ def run_external_command(func, *cmd, **kwargs): full_cmd = ' '.join(shlex_quote(x) for x in cmd) _LOGGER.info("Running: %s", full_cmd) - filter_lines = kwargs.get('filter_lines') orig_stdout = sys.stdout sys.stdout = RedirectText(sys.stdout, filter_lines=filter_lines) orig_stderr = sys.stderr sys.stderr = RedirectText(sys.stderr, filter_lines=filter_lines) - capture_stdout = kwargs.get('capture_stdout', False) if capture_stdout: cap_stdout = sys.stdout = io.StringIO()