_process_common.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. """Common utilities for the various process_* implementations.
  2. This file is only meant to be imported by the platform-specific implementations
  3. of subprocess utilities, and it contains tools that are common to all of them.
  4. """
  5. #-----------------------------------------------------------------------------
  6. # Copyright (C) 2010-2011 The IPython Development Team
  7. #
  8. # Distributed under the terms of the BSD License. The full license is in
  9. # the file COPYING, distributed as part of this software.
  10. #-----------------------------------------------------------------------------
  11. #-----------------------------------------------------------------------------
  12. # Imports
  13. #-----------------------------------------------------------------------------
  14. import os
  15. import shlex
  16. import subprocess
  17. import sys
  18. from typing import IO, List, TypeVar, Union
  19. from collections.abc import Callable
  20. _T = TypeVar("_T")
  21. from IPython.utils import py3compat
  22. #-----------------------------------------------------------------------------
  23. # Function definitions
  24. #-----------------------------------------------------------------------------
  25. def read_no_interrupt(stream: IO[bytes]) -> bytes | None:
  26. """Read from a pipe ignoring EINTR errors.
  27. This is necessary because when reading from pipes with GUI event loops
  28. running in the background, often interrupts are raised that stop the
  29. command from completing."""
  30. import errno
  31. try:
  32. return stream.read()
  33. except IOError as err:
  34. if err.errno != errno.EINTR:
  35. raise
  36. return None
  37. def process_handler(
  38. cmd: Union[str, List[str]],
  39. callback: Callable[[subprocess.Popen[bytes]], _T],
  40. stderr: int = subprocess.PIPE,
  41. ) -> _T | None:
  42. """Open a command in a shell subprocess and execute a callback.
  43. This function provides common scaffolding for creating subprocess.Popen()
  44. calls. It creates a Popen object and then calls the callback with it.
  45. Parameters
  46. ----------
  47. cmd : str or list
  48. A command to be executed by the system, using :class:`subprocess.Popen`.
  49. If a string is passed, it will be run in the system shell. If a list is
  50. passed, it will be used directly as arguments.
  51. callback : callable
  52. A one-argument function that will be called with the Popen object.
  53. stderr : file descriptor number, optional
  54. By default this is set to ``subprocess.PIPE``, but you can also pass the
  55. value ``subprocess.STDOUT`` to force the subprocess' stderr to go into
  56. the same file descriptor as its stdout. This is useful to read stdout
  57. and stderr combined in the order they are generated.
  58. Returns
  59. -------
  60. The return value of the provided callback is returned.
  61. """
  62. sys.stdout.flush()
  63. sys.stderr.flush()
  64. # On win32, close_fds can't be true when using pipes for stdin/out/err
  65. if sys.platform == "win32" and stderr != subprocess.PIPE:
  66. close_fds = False
  67. else:
  68. close_fds = True
  69. # Determine if cmd should be run with system shell.
  70. shell = isinstance(cmd, str)
  71. # On POSIX systems run shell commands with user-preferred shell.
  72. executable = None
  73. if shell and os.name == 'posix' and 'SHELL' in os.environ:
  74. executable = os.environ['SHELL']
  75. p = subprocess.Popen(cmd, shell=shell,
  76. executable=executable,
  77. stdin=subprocess.PIPE,
  78. stdout=subprocess.PIPE,
  79. stderr=stderr,
  80. close_fds=close_fds)
  81. try:
  82. out = callback(p)
  83. except KeyboardInterrupt:
  84. print('^C')
  85. sys.stdout.flush()
  86. sys.stderr.flush()
  87. out = None
  88. finally:
  89. # Make really sure that we don't leave processes behind, in case the
  90. # call above raises an exception
  91. # We start by assuming the subprocess finished (to avoid NameErrors
  92. # later depending on the path taken)
  93. if p.returncode is None:
  94. try:
  95. p.terminate()
  96. p.poll()
  97. except OSError:
  98. pass
  99. # One last try on our way out
  100. if p.returncode is None:
  101. try:
  102. p.kill()
  103. except OSError:
  104. pass
  105. return out
  106. def getoutput(cmd: str | list[str]) -> str:
  107. """Run a command and return its stdout/stderr as a string.
  108. Parameters
  109. ----------
  110. cmd : str or list
  111. A command to be executed in the system shell.
  112. Returns
  113. -------
  114. output : str
  115. A string containing the combination of stdout and stderr from the
  116. subprocess, in whatever order the subprocess originally wrote to its
  117. file descriptors (so the order of the information in this string is the
  118. correct order as would be seen if running the command in a terminal).
  119. """
  120. out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT)
  121. if out is None:
  122. return ''
  123. return py3compat.decode(out)
  124. def getoutputerror(cmd: str | list[str]) -> tuple[str, str]:
  125. """Return (standard output, standard error) of executing cmd in a shell.
  126. Accepts the same arguments as os.system().
  127. Parameters
  128. ----------
  129. cmd : str or list
  130. A command to be executed in the system shell.
  131. Returns
  132. -------
  133. stdout : str
  134. stderr : str
  135. """
  136. return get_output_error_code(cmd)[:2]
  137. def get_output_error_code(cmd: str | list[str]) -> tuple[str, str, int | None]:
  138. """Return (standard output, standard error, return code) of executing cmd
  139. in a shell.
  140. Accepts the same arguments as os.system().
  141. Parameters
  142. ----------
  143. cmd : str or list
  144. A command to be executed in the system shell.
  145. Returns
  146. -------
  147. stdout : str
  148. stderr : str
  149. returncode: int
  150. """
  151. result = process_handler(cmd, lambda p: (p.communicate(), p))
  152. if result is None:
  153. return '', '', None
  154. (out, err), p = result
  155. return py3compat.decode(out), py3compat.decode(err), p.returncode
  156. def arg_split(commandline: str, posix: bool = False, strict: bool = True) -> list[str]:
  157. """Split a command line's arguments in a shell-like manner.
  158. This is a modified version of the standard library's shlex.split()
  159. function, but with a default of posix=False for splitting, so that quotes
  160. in inputs are respected.
  161. if strict=False, then any errors shlex.split would raise will result in the
  162. unparsed remainder being the last element of the list, rather than raising.
  163. This is because we sometimes use arg_split to parse things other than
  164. command-line args.
  165. """
  166. lex = shlex.shlex(commandline, posix=posix)
  167. lex.whitespace_split = True
  168. # Extract tokens, ensuring that things like leaving open quotes
  169. # does not cause this to raise. This is important, because we
  170. # sometimes pass Python source through this (e.g. %timeit f(" ")),
  171. # and it shouldn't raise an exception.
  172. # It may be a bad idea to parse things that are not command-line args
  173. # through this function, but we do, so let's be safe about it.
  174. lex.commenters='' #fix for GH-1269
  175. tokens = []
  176. while True:
  177. try:
  178. tokens.append(next(lex))
  179. except StopIteration:
  180. break
  181. except ValueError:
  182. if strict:
  183. raise
  184. # couldn't parse, get remaining blob as last token
  185. tokens.append(lex.token)
  186. break
  187. return tokens