44 lines
1.0 KiB
Python
44 lines
1.0 KiB
Python
__all__ = (
|
|
"CommandError",
|
|
"CommandExecutor",
|
|
)
|
|
|
|
|
|
import logging
|
|
import subprocess
|
|
from pathlib import Path
|
|
|
|
logger = logging.getLogger("command")
|
|
|
|
|
|
class CommandError(RuntimeError):
|
|
@property
|
|
def output(self):
|
|
return self.args[0].decode("utf-8").strip()
|
|
|
|
|
|
class CommandExecutor:
|
|
_logger = logger
|
|
|
|
def __init__(self, command: str) -> None:
|
|
self._command = command
|
|
|
|
def run(self, basepath: Path):
|
|
self._logger.debug(self._command)
|
|
result = subprocess.run(
|
|
self._command.split(" "),
|
|
cwd=basepath,
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.PIPE,
|
|
)
|
|
self._logstd(result.stdout, logging.TRACE)
|
|
self._logstd(result.stderr, logging.TRACE)
|
|
if result.returncode != 0:
|
|
raise CommandError(result.stderr)
|
|
|
|
@classmethod
|
|
def _logstd(cls, data: bytes, level: int):
|
|
if data:
|
|
output = data.decode("utf-8").strip()
|
|
cls._logger.log(level, f"\n{output}\n")
|