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

76 行
2.6 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, its stdout output, and its stderr 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. stderr = []
  29. stderrBuf = b''
  30. if input is not None:
  31. stdinView = memoryview(input)
  32. stdinOffset = 0
  33. PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
  34. while sel.get_map():
  35. for key, _ in sel.select():
  36. if key.fileobj is p.stdin:
  37. try:
  38. stdinOffset += os.write(key.fd, stdinView[stdinOffset : stdinOffset + PIPE_BUF])
  39. except BrokenPipeError:
  40. sel.unregister(key.fileobj)
  41. key.fileobj.close()
  42. else:
  43. if stdinOffset >= len(input):
  44. sel.unregister(key.fileobj)
  45. key.fileobj.close()
  46. else:
  47. data = key.fileobj.read1()
  48. if not data:
  49. sel.unregister(key.fileobj)
  50. key.fileobj.close()
  51. continue
  52. if key.fileobj is p.stderr:
  53. stderr.append(data)
  54. stderrBuf += data
  55. *lines, stderrBuf = stderrBuf.replace(b'\r', b'\n').rsplit(b'\n', 1)
  56. if not lines:
  57. continue
  58. lines = lines[0].decode('utf-8').split('\n')
  59. for line in lines:
  60. _logger.info(line)
  61. else:
  62. stdout.append(data)
  63. if stderrBuf:
  64. _logger.info(stderrBuf.decode('utf-8'))
  65. assert p.poll() is not None
  66. if input is not None and stdinOffset < len(input):
  67. _logger.warning(f'Could not write all input to the stdin pipe (wanted to write {len(input)} bytes, only wrote {stdinOffset})')
  68. _logger.info(f'Process exited with status {p.returncode}')
  69. if check and p.returncode != 0:
  70. raise subprocess.CalledProcessError(returncode = p.returncode, cmd = args)
  71. return (p.returncode, b''.join(stdout).decode('utf-8'), b''.join(stderr).decode('utf-8'))