_process_posix.py 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. """Posix-specific implementation of process utilities.
  2. This file is only meant to be imported by process.py, not by end-users.
  3. """
  4. #-----------------------------------------------------------------------------
  5. # Copyright (C) 2010-2011 The IPython Development Team
  6. #
  7. # Distributed under the terms of the BSD License. The full license is in
  8. # the file COPYING, distributed as part of this software.
  9. #-----------------------------------------------------------------------------
  10. #-----------------------------------------------------------------------------
  11. # Imports
  12. #-----------------------------------------------------------------------------
  13. # Stdlib
  14. import errno
  15. import os
  16. import subprocess as sp
  17. import sys
  18. import pexpect
  19. # Our own
  20. from ._process_common import getoutput, arg_split
  21. from IPython.utils.encoding import DEFAULT_ENCODING
  22. #-----------------------------------------------------------------------------
  23. # Function definitions
  24. #-----------------------------------------------------------------------------
  25. class ProcessHandler(object):
  26. """Execute subprocesses under the control of pexpect.
  27. """
  28. # Timeout in seconds to wait on each reading of the subprocess' output.
  29. # This should not be set too low to avoid cpu overusage from our side,
  30. # since we read in a loop whose period is controlled by this timeout.
  31. read_timeout = 0.05
  32. # Timeout to give a process if we receive SIGINT, between sending the
  33. # SIGINT to the process and forcefully terminating it.
  34. terminate_timeout = 0.2
  35. # File object where stdout and stderr of the subprocess will be written
  36. logfile = None
  37. # Shell to call for subprocesses to execute
  38. _sh = None
  39. @property
  40. def sh(self):
  41. if self._sh is None:
  42. shell_name = os.environ.get("SHELL", "sh")
  43. self._sh = pexpect.which(shell_name)
  44. if self._sh is None:
  45. raise OSError('"{}" shell not found'.format(shell_name))
  46. return self._sh
  47. def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None):
  48. """Arguments are used for pexpect calls."""
  49. self.read_timeout = (ProcessHandler.read_timeout if read_timeout is
  50. None else read_timeout)
  51. self.terminate_timeout = (ProcessHandler.terminate_timeout if
  52. terminate_timeout is None else
  53. terminate_timeout)
  54. self.logfile = sys.stdout if logfile is None else logfile
  55. def getoutput(self, cmd):
  56. """Run a command and return its stdout/stderr as a string.
  57. Parameters
  58. ----------
  59. cmd : str
  60. A command to be executed in the system shell.
  61. Returns
  62. -------
  63. output : str
  64. A string containing the combination of stdout and stderr from the
  65. subprocess, in whatever order the subprocess originally wrote to its
  66. file descriptors (so the order of the information in this string is the
  67. correct order as would be seen if running the command in a terminal).
  68. """
  69. try:
  70. return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
  71. except KeyboardInterrupt:
  72. print('^C', file=sys.stderr, end='')
  73. def getoutput_pexpect(self, cmd):
  74. """Run a command and return its stdout/stderr as a string.
  75. Parameters
  76. ----------
  77. cmd : str
  78. A command to be executed in the system shell.
  79. Returns
  80. -------
  81. output : str
  82. A string containing the combination of stdout and stderr from the
  83. subprocess, in whatever order the subprocess originally wrote to its
  84. file descriptors (so the order of the information in this string is the
  85. correct order as would be seen if running the command in a terminal).
  86. """
  87. try:
  88. return pexpect.run(self.sh, args=['-c', cmd]).replace('\r\n', '\n')
  89. except KeyboardInterrupt:
  90. print('^C', file=sys.stderr, end='')
  91. def system(self, cmd):
  92. """Execute a command in a subshell.
  93. Parameters
  94. ----------
  95. cmd : str
  96. A command to be executed in the system shell.
  97. Returns
  98. -------
  99. int : child's exitstatus
  100. """
  101. # Get likely encoding for the output.
  102. enc = DEFAULT_ENCODING
  103. # Patterns to match on the output, for pexpect. We read input and
  104. # allow either a short timeout or EOF
  105. patterns = [pexpect.TIMEOUT, pexpect.EOF]
  106. # the index of the EOF pattern in the list.
  107. # even though we know it's 1, this call means we don't have to worry if
  108. # we change the above list, and forget to change this value:
  109. EOF_index = patterns.index(pexpect.EOF)
  110. # The size of the output stored so far in the process output buffer.
  111. # Since pexpect only appends to this buffer, each time we print we
  112. # record how far we've printed, so that next time we only print *new*
  113. # content from the buffer.
  114. out_size = 0
  115. try:
  116. # Since we're not really searching the buffer for text patterns, we
  117. # can set pexpect's search window to be tiny and it won't matter.
  118. # We only search for the 'patterns' timeout or EOF, which aren't in
  119. # the text itself.
  120. #child = pexpect.spawn(pcmd, searchwindowsize=1)
  121. if hasattr(pexpect, 'spawnb'):
  122. child = pexpect.spawnb(self.sh, args=['-c', cmd]) # Pexpect-U
  123. else:
  124. child = pexpect.spawn(self.sh, args=['-c', cmd]) # Vanilla Pexpect
  125. flush = sys.stdout.flush
  126. while True:
  127. # res is the index of the pattern that caused the match, so we
  128. # know whether we've finished (if we matched EOF) or not
  129. res_idx = child.expect_list(patterns, self.read_timeout)
  130. print(child.before[out_size:].decode(enc, 'replace'), end='')
  131. flush()
  132. if res_idx==EOF_index:
  133. break
  134. # Update the pointer to what we've already printed
  135. out_size = len(child.before)
  136. except KeyboardInterrupt:
  137. # We need to send ^C to the process. The ascii code for '^C' is 3
  138. # (the character is known as ETX for 'End of Text', see
  139. # curses.ascii.ETX).
  140. child.sendline(chr(3))
  141. # Read and print any more output the program might produce on its
  142. # way out.
  143. try:
  144. out_size = len(child.before)
  145. child.expect_list(patterns, self.terminate_timeout)
  146. print(child.before[out_size:].decode(enc, 'replace'), end='')
  147. sys.stdout.flush()
  148. except KeyboardInterrupt:
  149. # Impatient users tend to type it multiple times
  150. pass
  151. finally:
  152. # Ensure the subprocess really is terminated
  153. child.terminate(force=True)
  154. # add isalive check, to ensure exitstatus is set:
  155. child.isalive()
  156. # We follow the subprocess pattern, returning either the exit status
  157. # as a positive number, or the terminating signal as a negative
  158. # number.
  159. # on Linux, sh returns 128+n for signals terminating child processes on Linux
  160. # on BSD (OS X), the signal code is set instead
  161. if child.exitstatus is None:
  162. # on WIFSIGNALED, pexpect sets signalstatus, leaving exitstatus=None
  163. if child.signalstatus is None:
  164. # this condition may never occur,
  165. # but let's be certain we always return an integer.
  166. return 0
  167. return -child.signalstatus
  168. if child.exitstatus > 128:
  169. return -(child.exitstatus - 128)
  170. return child.exitstatus
  171. # Make system() with a functional interface for outside use. Note that we use
  172. # getoutput() from the _common utils, which is built on top of popen(). Using
  173. # pexpect to get subprocess output produces difficult to parse output, since
  174. # programs think they are talking to a tty and produce highly formatted output
  175. # (ls is a good example) that makes them hard.
  176. system = ProcessHandler().system
  177. def check_pid(pid):
  178. try:
  179. os.kill(pid, 0)
  180. except OSError as err:
  181. if err.errno == errno.ESRCH:
  182. return False
  183. elif err.errno == errno.EPERM:
  184. # Don't have permission to signal the process - probably means it exists
  185. return True
  186. raise
  187. else:
  188. return True