Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

proc.py 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. from pathlib import PurePath, Path
  2. from typing import Iterable, Union
  3. import subprocess
  4. CommandLineArg = Union[str, PurePath, int, float]
  5. CommandLineArg1 = Union[CommandLineArg, Iterable[CommandLineArg]]
  6. CommandLineArg2 = Union[CommandLineArg1, Iterable[CommandLineArg1]]
  7. CommandLineArg3 = Union[CommandLineArg2, Iterable[CommandLineArg2]]
  8. CommandLineArg4 = Union[CommandLineArg3, Iterable[CommandLineArg3]]
  9. CommandLine = Union[CommandLineArg4, Iterable[CommandLineArg4]]
  10. def flatten_cmd(cmd: CommandLine) -> Iterable[str]:
  11. if isinstance(cmd, (str, PurePath)):
  12. yield str(cmd)
  13. elif isinstance(cmd, (int, float)):
  14. yield str(cmd)
  15. elif hasattr(cmd, '__iter__'):
  16. each = (flatten_cmd(arg) for arg in cmd) # type: ignore
  17. for item in each:
  18. yield from item
  19. else:
  20. assert False, f'Invalid command line element: {repr(cmd)}'
  21. def run(*cmd: CommandLine, cwd: Path = None) -> subprocess.CompletedProcess:
  22. return subprocess.run(
  23. list(flatten_cmd(cmd)), # type: ignore
  24. cwd=cwd,
  25. )
  26. def check_run(*cmd: CommandLine,
  27. cwd: Path = None) -> subprocess.CompletedProcess:
  28. flat_cmd = list(flatten_cmd(cmd)) # type: ignore
  29. res = run(flat_cmd, cwd=cwd)
  30. if res.returncode != 0:
  31. raise subprocess.CalledProcessError(res.returncode, flat_cmd)
  32. return res