您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

40 行
1.3KB

  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