A VCS repository archival tool
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

74 řádky
2.5 KiB

  1. import logging
  2. import os
  3. import select
  4. import selectors
  5. import subprocess
  6. _logger = logging.getLogger(__name__)
  7. def run_with_log(args, *, check = True, input = None, **kwargs):
  8. '''
  9. Run a command using `subprocess.Popen(args, **kwargs)` and log all its stderr output via `logging`.
  10. `check` has the same semantics as on `subprocess.run`, i.e. raises an exception if the process exits non-zero.
  11. `input`, if specified, is a `bytes` object that is fed to the subprocess via stdin.
  12. `stdin`, `stdout`, and `stderr` kwargs must not be used.
  13. Returns a tuple with the process's exit status and its stdout output.
  14. '''
  15. badKwargs = {'stdin', 'stdout', 'stderr'}.intersection(set(kwargs))
  16. if badKwargs:
  17. raise ValueError(f'Disallowed kwargs: {", ".join(sorted(badKwargs))}')
  18. _logger.info(f'Running subprocess: {args!r}')
  19. if input is not None:
  20. kwargs['stdin'] = subprocess.PIPE
  21. p = subprocess.Popen(args, **kwargs, stdout = subprocess.PIPE, stderr = subprocess.PIPE)
  22. sel = selectors.DefaultSelector()
  23. if input is not None:
  24. sel.register(p.stdin, selectors.EVENT_WRITE)
  25. sel.register(p.stdout, selectors.EVENT_READ)
  26. sel.register(p.stderr, selectors.EVENT_READ)
  27. stdout = []
  28. stderrBuf = b''
  29. if input is not None:
  30. stdinView = memoryview(input)
  31. stdinOffset = 0
  32. PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
  33. while sel.get_map():
  34. for key, _ in sel.select():
  35. if key.fileobj is p.stdin:
  36. try:
  37. stdinOffset += os.write(key.fd, stdinView[stdinOffset : stdinOffset + PIPE_BUF])
  38. except BrokenPipeError:
  39. sel.unregister(key.fileobj)
  40. key.fileobj.close()
  41. else:
  42. if stdinOffset >= len(input):
  43. sel.unregister(key.fileobj)
  44. key.fileobj.close()
  45. else:
  46. data = key.fileobj.read1()
  47. if not data:
  48. sel.unregister(key.fileobj)
  49. key.fileobj.close()
  50. continue
  51. if key.fileobj is p.stderr:
  52. stderrBuf += data
  53. *lines, stderrBuf = stderrBuf.replace(b'\r', b'\n').rsplit(b'\n', 1)
  54. if not lines:
  55. continue
  56. lines = lines[0].decode('utf-8').split('\n')
  57. for line in lines:
  58. _logger.info(line)
  59. else:
  60. stdout.append(data)
  61. if stderrBuf:
  62. _logger.info(stderrBuf.decode('utf-8'))
  63. assert p.poll() is not None
  64. if input is not None and stdinOffset < len(input):
  65. _logger.warning(f'Could not write all input to the stdin pipe (wanted to write {len(input)} bytes, only wrote {stdinOffset})')
  66. _logger.info(f'Process exited with status {p.returncode}')
  67. if check and p.returncode != 0:
  68. raise subprocess.CalledProcessError(returncode = p.returncode, cmd = args)
  69. return (p.returncode, b''.join(stdout).decode('utf-8'))