subprocess.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. # The following comment should be removed at some point in the future.
  2. # mypy: strict-optional=False
  3. from __future__ import absolute_import
  4. import logging
  5. import os
  6. import subprocess
  7. from pip._vendor.six.moves import shlex_quote
  8. from pip._internal.cli.spinners import SpinnerInterface, open_spinner
  9. from pip._internal.exceptions import InstallationError
  10. from pip._internal.utils.compat import console_to_str, str_to_display
  11. from pip._internal.utils.logging import subprocess_logger
  12. from pip._internal.utils.misc import HiddenText, path_to_display
  13. from pip._internal.utils.typing import MYPY_CHECK_RUNNING
  14. if MYPY_CHECK_RUNNING:
  15. from typing import (
  16. Any, Callable, Iterable, List, Mapping, Optional, Text, Union,
  17. )
  18. CommandArgs = List[Union[str, HiddenText]]
  19. LOG_DIVIDER = '----------------------------------------'
  20. def make_command(*args):
  21. # type: (Union[str, HiddenText, CommandArgs]) -> CommandArgs
  22. """
  23. Create a CommandArgs object.
  24. """
  25. command_args = [] # type: CommandArgs
  26. for arg in args:
  27. # Check for list instead of CommandArgs since CommandArgs is
  28. # only known during type-checking.
  29. if isinstance(arg, list):
  30. command_args.extend(arg)
  31. else:
  32. # Otherwise, arg is str or HiddenText.
  33. command_args.append(arg)
  34. return command_args
  35. def format_command_args(args):
  36. # type: (Union[List[str], CommandArgs]) -> str
  37. """
  38. Format command arguments for display.
  39. """
  40. # For HiddenText arguments, display the redacted form by calling str().
  41. # Also, we don't apply str() to arguments that aren't HiddenText since
  42. # this can trigger a UnicodeDecodeError in Python 2 if the argument
  43. # has type unicode and includes a non-ascii character. (The type
  44. # checker doesn't ensure the annotations are correct in all cases.)
  45. return ' '.join(
  46. shlex_quote(str(arg)) if isinstance(arg, HiddenText)
  47. else shlex_quote(arg) for arg in args
  48. )
  49. def reveal_command_args(args):
  50. # type: (Union[List[str], CommandArgs]) -> List[str]
  51. """
  52. Return the arguments in their raw, unredacted form.
  53. """
  54. return [
  55. arg.secret if isinstance(arg, HiddenText) else arg for arg in args
  56. ]
  57. def make_subprocess_output_error(
  58. cmd_args, # type: Union[List[str], CommandArgs]
  59. cwd, # type: Optional[str]
  60. lines, # type: List[Text]
  61. exit_status, # type: int
  62. ):
  63. # type: (...) -> Text
  64. """
  65. Create and return the error message to use to log a subprocess error
  66. with command output.
  67. :param lines: A list of lines, each ending with a newline.
  68. """
  69. command = format_command_args(cmd_args)
  70. # Convert `command` and `cwd` to text (unicode in Python 2) so we can use
  71. # them as arguments in the unicode format string below. This avoids
  72. # "UnicodeDecodeError: 'ascii' codec can't decode byte ..." in Python 2
  73. # if either contains a non-ascii character.
  74. command_display = str_to_display(command, desc='command bytes')
  75. cwd_display = path_to_display(cwd)
  76. # We know the joined output value ends in a newline.
  77. output = ''.join(lines)
  78. msg = (
  79. # Use a unicode string to avoid "UnicodeEncodeError: 'ascii'
  80. # codec can't encode character ..." in Python 2 when a format
  81. # argument (e.g. `output`) has a non-ascii character.
  82. u'Command errored out with exit status {exit_status}:\n'
  83. ' command: {command_display}\n'
  84. ' cwd: {cwd_display}\n'
  85. 'Complete output ({line_count} lines):\n{output}{divider}'
  86. ).format(
  87. exit_status=exit_status,
  88. command_display=command_display,
  89. cwd_display=cwd_display,
  90. line_count=len(lines),
  91. output=output,
  92. divider=LOG_DIVIDER,
  93. )
  94. return msg
  95. def call_subprocess(
  96. cmd, # type: Union[List[str], CommandArgs]
  97. show_stdout=False, # type: bool
  98. cwd=None, # type: Optional[str]
  99. on_returncode='raise', # type: str
  100. extra_ok_returncodes=None, # type: Optional[Iterable[int]]
  101. command_desc=None, # type: Optional[str]
  102. extra_environ=None, # type: Optional[Mapping[str, Any]]
  103. unset_environ=None, # type: Optional[Iterable[str]]
  104. spinner=None, # type: Optional[SpinnerInterface]
  105. log_failed_cmd=True # type: Optional[bool]
  106. ):
  107. # type: (...) -> Text
  108. """
  109. Args:
  110. show_stdout: if true, use INFO to log the subprocess's stderr and
  111. stdout streams. Otherwise, use DEBUG. Defaults to False.
  112. extra_ok_returncodes: an iterable of integer return codes that are
  113. acceptable, in addition to 0. Defaults to None, which means [].
  114. unset_environ: an iterable of environment variable names to unset
  115. prior to calling subprocess.Popen().
  116. log_failed_cmd: if false, failed commands are not logged, only raised.
  117. """
  118. if extra_ok_returncodes is None:
  119. extra_ok_returncodes = []
  120. if unset_environ is None:
  121. unset_environ = []
  122. # Most places in pip use show_stdout=False. What this means is--
  123. #
  124. # - We connect the child's output (combined stderr and stdout) to a
  125. # single pipe, which we read.
  126. # - We log this output to stderr at DEBUG level as it is received.
  127. # - If DEBUG logging isn't enabled (e.g. if --verbose logging wasn't
  128. # requested), then we show a spinner so the user can still see the
  129. # subprocess is in progress.
  130. # - If the subprocess exits with an error, we log the output to stderr
  131. # at ERROR level if it hasn't already been displayed to the console
  132. # (e.g. if --verbose logging wasn't enabled). This way we don't log
  133. # the output to the console twice.
  134. #
  135. # If show_stdout=True, then the above is still done, but with DEBUG
  136. # replaced by INFO.
  137. if show_stdout:
  138. # Then log the subprocess output at INFO level.
  139. log_subprocess = subprocess_logger.info
  140. used_level = logging.INFO
  141. else:
  142. # Then log the subprocess output using DEBUG. This also ensures
  143. # it will be logged to the log file (aka user_log), if enabled.
  144. log_subprocess = subprocess_logger.debug
  145. used_level = logging.DEBUG
  146. # Whether the subprocess will be visible in the console.
  147. showing_subprocess = subprocess_logger.getEffectiveLevel() <= used_level
  148. # Only use the spinner if we're not showing the subprocess output
  149. # and we have a spinner.
  150. use_spinner = not showing_subprocess and spinner is not None
  151. if command_desc is None:
  152. command_desc = format_command_args(cmd)
  153. log_subprocess("Running command %s", command_desc)
  154. env = os.environ.copy()
  155. if extra_environ:
  156. env.update(extra_environ)
  157. for name in unset_environ:
  158. env.pop(name, None)
  159. try:
  160. proc = subprocess.Popen(
  161. # Convert HiddenText objects to the underlying str.
  162. reveal_command_args(cmd),
  163. stderr=subprocess.STDOUT, stdin=subprocess.PIPE,
  164. stdout=subprocess.PIPE, cwd=cwd, env=env,
  165. )
  166. proc.stdin.close()
  167. except Exception as exc:
  168. if log_failed_cmd:
  169. subprocess_logger.critical(
  170. "Error %s while executing command %s", exc, command_desc,
  171. )
  172. raise
  173. all_output = []
  174. while True:
  175. # The "line" value is a unicode string in Python 2.
  176. line = console_to_str(proc.stdout.readline())
  177. if not line:
  178. break
  179. line = line.rstrip()
  180. all_output.append(line + '\n')
  181. # Show the line immediately.
  182. log_subprocess(line)
  183. # Update the spinner.
  184. if use_spinner:
  185. spinner.spin()
  186. try:
  187. proc.wait()
  188. finally:
  189. if proc.stdout:
  190. proc.stdout.close()
  191. proc_had_error = (
  192. proc.returncode and proc.returncode not in extra_ok_returncodes
  193. )
  194. if use_spinner:
  195. if proc_had_error:
  196. spinner.finish("error")
  197. else:
  198. spinner.finish("done")
  199. if proc_had_error:
  200. if on_returncode == 'raise':
  201. if not showing_subprocess and log_failed_cmd:
  202. # Then the subprocess streams haven't been logged to the
  203. # console yet.
  204. msg = make_subprocess_output_error(
  205. cmd_args=cmd,
  206. cwd=cwd,
  207. lines=all_output,
  208. exit_status=proc.returncode,
  209. )
  210. subprocess_logger.error(msg)
  211. exc_msg = (
  212. 'Command errored out with exit status {}: {} '
  213. 'Check the logs for full command output.'
  214. ).format(proc.returncode, command_desc)
  215. raise InstallationError(exc_msg)
  216. elif on_returncode == 'warn':
  217. subprocess_logger.warning(
  218. 'Command "{}" had error code {} in {}'.format(
  219. command_desc, proc.returncode, cwd)
  220. )
  221. elif on_returncode == 'ignore':
  222. pass
  223. else:
  224. raise ValueError('Invalid value: on_returncode={!r}'.format(
  225. on_returncode))
  226. return ''.join(all_output)
  227. def runner_with_spinner_message(message):
  228. # type: (str) -> Callable[..., None]
  229. """Provide a subprocess_runner that shows a spinner message.
  230. Intended for use with for pep517's Pep517HookCaller. Thus, the runner has
  231. an API that matches what's expected by Pep517HookCaller.subprocess_runner.
  232. """
  233. def runner(
  234. cmd, # type: List[str]
  235. cwd=None, # type: Optional[str]
  236. extra_environ=None # type: Optional[Mapping[str, Any]]
  237. ):
  238. # type: (...) -> None
  239. with open_spinner(message) as spinner:
  240. call_subprocess(
  241. cmd,
  242. cwd=cwd,
  243. extra_environ=extra_environ,
  244. spinner=spinner,
  245. )
  246. return runner