_process_posix.py 8.5 KB

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