You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

subprocess.py 9.7KB

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