_process_common.py 6.8 KB

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