|
1 | | -import shutil |
2 | | -import subprocess # nosec |
3 | | -from pathlib import Path |
4 | | -from typing import Any |
5 | | - |
6 | | -from .exceptions import UserNotificationException |
7 | | -from .logging import logger |
8 | | - |
9 | | - |
10 | | -def which(app_name: str) -> Path | None: |
11 | | - """Return the path to the app if it is in the PATH, otherwise return None.""" |
12 | | - app_path = shutil.which(app_name) |
13 | | - return Path(app_path) if app_path else None |
14 | | - |
15 | | - |
16 | | -class SubprocessExecutor: |
17 | | - """ |
18 | | - Execute a command in a subprocess. |
19 | | -
|
20 | | - Args: |
21 | | - ---- |
22 | | - capture_output: If True, the output of the command will be captured. |
23 | | - print_output: If True, the output of the command will be printed to the logger. |
24 | | - One can set this to false in order to get the output in the returned CompletedProcess object. |
25 | | -
|
26 | | - """ |
27 | | - |
28 | | - def __init__( |
29 | | - self, |
30 | | - command: str | list[str | Path], |
31 | | - cwd: Path | None = None, |
32 | | - capture_output: bool = True, |
33 | | - env: dict[str, str] | None = None, |
34 | | - shell: bool = False, |
35 | | - print_output: bool = True, |
36 | | - ): |
37 | | - self.logger = logger.bind() |
38 | | - self.command = command |
39 | | - self.current_working_directory = cwd |
40 | | - self.capture_output = capture_output |
41 | | - self.env = env |
42 | | - self.shell = shell |
43 | | - self.print_output = print_output |
44 | | - |
45 | | - @property |
46 | | - def command_str(self) -> str: |
47 | | - if isinstance(self.command, str): |
48 | | - return self.command |
49 | | - return " ".join(str(arg) if not isinstance(arg, str) else arg for arg in self.command) |
50 | | - |
51 | | - def execute(self, handle_errors: bool = True) -> subprocess.CompletedProcess[Any] | None: |
52 | | - """Execute the command and return the CompletedProcess object if handle_errors is False.""" |
53 | | - try: |
54 | | - completed_process = None |
55 | | - stdout = "" |
56 | | - stderr = "" |
57 | | - self.logger.info(f"Running command: {self.command_str}") |
58 | | - cwd_path = (self.current_working_directory or Path.cwd()).as_posix() |
59 | | - with subprocess.Popen( |
60 | | - args=self.command, |
61 | | - cwd=cwd_path, |
62 | | - stdout=(subprocess.PIPE if self.capture_output else subprocess.DEVNULL), |
63 | | - stderr=(subprocess.STDOUT if self.capture_output else subprocess.DEVNULL), |
64 | | - text=True, |
65 | | - env=self.env, |
66 | | - shell=self.shell, |
67 | | - ) as process: # nosec |
68 | | - if self.capture_output and process.stdout is not None: |
69 | | - if self.print_output: |
70 | | - for line in iter(process.stdout.readline, ""): |
71 | | - self.logger.info(line.strip()) |
72 | | - process.wait() |
73 | | - else: |
74 | | - stdout, stderr = process.communicate() |
75 | | - |
76 | | - if handle_errors: |
77 | | - # Check return code |
78 | | - if process.returncode != 0: |
79 | | - raise subprocess.CalledProcessError(process.returncode, self.command_str) |
80 | | - else: |
81 | | - completed_process = subprocess.CompletedProcess(process.args, process.returncode, stdout, stderr) |
82 | | - except subprocess.CalledProcessError as e: |
83 | | - raise UserNotificationException(f"Command '{self.command_str}' execution failed with return code {e.returncode}") from None |
84 | | - except FileNotFoundError as e: |
85 | | - raise UserNotificationException(f"Command '{self.command_str}' could not be executed. Failed with error {e}") from None |
86 | | - except KeyboardInterrupt: |
87 | | - raise UserNotificationException(f"Command '{self.command_str}' execution interrupted by user") from None |
88 | | - return completed_process |
| 1 | +import locale |
| 2 | +import shutil |
| 3 | +import subprocess # nosec |
| 4 | +from pathlib import Path |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +from .exceptions import UserNotificationException |
| 8 | +from .logging import logger |
| 9 | + |
| 10 | + |
| 11 | +def which(app_name: str) -> Path | None: |
| 12 | + """Return the path to the app if it is in the PATH, otherwise return None.""" |
| 13 | + app_path = shutil.which(app_name) |
| 14 | + return Path(app_path) if app_path else None |
| 15 | + |
| 16 | + |
| 17 | +class SubprocessExecutor: |
| 18 | + """ |
| 19 | + Execute a command in a subprocess. |
| 20 | +
|
| 21 | + Args: |
| 22 | + ---- |
| 23 | + capture_output: If True, the output of the command will be captured. |
| 24 | + print_output: If True, the output of the command will be printed to the logger. |
| 25 | + One can set this to false in order to get the output in the returned CompletedProcess object. |
| 26 | +
|
| 27 | + """ |
| 28 | + |
| 29 | + def __init__( |
| 30 | + self, |
| 31 | + command: str | list[str | Path], |
| 32 | + cwd: Path | None = None, |
| 33 | + capture_output: bool = True, |
| 34 | + env: dict[str, str] | None = None, |
| 35 | + shell: bool = False, |
| 36 | + print_output: bool = True, |
| 37 | + ): |
| 38 | + self.logger = logger.bind() |
| 39 | + self.command = command |
| 40 | + self.current_working_directory = cwd |
| 41 | + self.capture_output = capture_output |
| 42 | + self.env = env |
| 43 | + self.shell = shell |
| 44 | + self.print_output = print_output |
| 45 | + |
| 46 | + @property |
| 47 | + def command_str(self) -> str: |
| 48 | + if isinstance(self.command, str): |
| 49 | + return self.command |
| 50 | + return " ".join(str(arg) if not isinstance(arg, str) else arg for arg in self.command) |
| 51 | + |
| 52 | + def execute(self, handle_errors: bool = True) -> subprocess.CompletedProcess[Any] | None: |
| 53 | + """Execute the command and return the CompletedProcess object if handle_errors is False.""" |
| 54 | + try: |
| 55 | + completed_process = None |
| 56 | + stdout = "" |
| 57 | + stderr = "" |
| 58 | + self.logger.info(f"Running command: {self.command_str}") |
| 59 | + cwd_path = (self.current_working_directory or Path.cwd()).as_posix() |
| 60 | + with subprocess.Popen( |
| 61 | + args=self.command, |
| 62 | + cwd=cwd_path, |
| 63 | + # Combine both streams to stdout (when captured) |
| 64 | + stdout=(subprocess.PIPE if self.capture_output else subprocess.DEVNULL), |
| 65 | + stderr=(subprocess.STDOUT if self.capture_output else subprocess.DEVNULL), |
| 66 | + # enables line buffering, line is flushed after each \n |
| 67 | + bufsize=1, |
| 68 | + text=True, |
| 69 | + # every new line is a \n |
| 70 | + universal_newlines=True, |
| 71 | + # decode bytes to str using current locale/system encoding |
| 72 | + encoding=locale.getpreferredencoding(False), |
| 73 | + # replace unknown characters with � |
| 74 | + errors="replace", |
| 75 | + env=self.env, |
| 76 | + shell=self.shell, |
| 77 | + ) as process: # nosec |
| 78 | + if self.capture_output and process.stdout is not None: |
| 79 | + if self.print_output: |
| 80 | + for line in iter(process.stdout.readline, ""): |
| 81 | + self.logger.info(line.strip()) |
| 82 | + stdout += line |
| 83 | + process.wait() |
| 84 | + else: |
| 85 | + stdout, stderr = process.communicate() |
| 86 | + |
| 87 | + if handle_errors: |
| 88 | + # Check return code |
| 89 | + if process.returncode != 0: |
| 90 | + raise subprocess.CalledProcessError(process.returncode, self.command_str) |
| 91 | + else: |
| 92 | + completed_process = subprocess.CompletedProcess(process.args, process.returncode, stdout, stderr) |
| 93 | + except subprocess.CalledProcessError as e: |
| 94 | + raise UserNotificationException(f"Command '{self.command_str}' execution failed with return code {e.returncode}") from None |
| 95 | + except FileNotFoundError as e: |
| 96 | + raise UserNotificationException(f"Command '{self.command_str}' could not be executed. Failed with error {e}") from None |
| 97 | + except KeyboardInterrupt: |
| 98 | + raise UserNotificationException(f"Command '{self.command_str}' execution interrupted by user") from None |
| 99 | + return completed_process |
0 commit comments