ptyprocess.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. # -*- coding: utf-8 -*-
  2. # Standard library imports
  3. import codecs
  4. import os
  5. import shlex
  6. import signal
  7. import socket
  8. import subprocess
  9. import threading
  10. import time
  11. try:
  12. from shutil import which
  13. except ImportError:
  14. from backports.shutil_which import which
  15. # Local imports
  16. from .winpty_wrapper import PTY, PY2
  17. class PtyProcess(object):
  18. """This class represents a process running in a pseudoterminal.
  19. The main constructor is the :meth:`spawn` classmethod.
  20. """
  21. def __init__(self, pty):
  22. assert isinstance(pty, PTY)
  23. self.pty = pty
  24. self.pid = pty.pid
  25. self.read_blocking = bool(os.environ.get('PYWINPTY_BLOCK', 1))
  26. self.closed = False
  27. self.flag_eof = False
  28. self.decoder = codecs.getincrementaldecoder('utf-8')(errors='strict')
  29. # Used by terminate() to give kernel time to update process status.
  30. # Time in seconds.
  31. self.delayafterterminate = 0.1
  32. # Used by close() to give kernel time to update process status.
  33. # Time in seconds.
  34. self.delayafterclose = 0.1
  35. # Set up our file reader sockets.
  36. self._server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  37. self._server.bind(("127.0.0.1", 0))
  38. address = self._server.getsockname()
  39. self._server.listen(1)
  40. # Read from the pty in a thread.
  41. self._thread = threading.Thread(target=_read_in_thread,
  42. args=(address, self.pty, self.read_blocking))
  43. self._thread.setDaemon(True)
  44. self._thread.start()
  45. self.fileobj, _ = self._server.accept()
  46. self.fd = self.fileobj.fileno()
  47. @classmethod
  48. def spawn(cls, argv, cwd=None, env=None, dimensions=(24, 80)):
  49. """Start the given command in a child process in a pseudo terminal.
  50. This does all the setting up the pty, and returns an instance of
  51. PtyProcess.
  52. Dimensions of the psuedoterminal used for the subprocess can be
  53. specified as a tuple (rows, cols), or the default (24, 80) will be
  54. used.
  55. """
  56. if isinstance(argv, str):
  57. argv = shlex.split(argv, posix=False)
  58. if not isinstance(argv, (list, tuple)):
  59. raise TypeError("Expected a list or tuple for argv, got %r" % argv)
  60. # Shallow copy of argv so we can modify it
  61. argv = argv[:]
  62. command = argv[0]
  63. env = env or os.environ
  64. path = env.get('PATH', os.defpath)
  65. command_with_path = which(command, path=path)
  66. if command_with_path is None:
  67. raise FileNotFoundError(
  68. 'The command was not found or was not ' +
  69. 'executable: %s.' % command
  70. )
  71. command = command_with_path
  72. argv[0] = command
  73. cmdline = ' ' + subprocess.list2cmdline(argv[1:])
  74. cwd = cwd or os.getcwd()
  75. proc = PTY(dimensions[1], dimensions[0])
  76. # Create the environemnt string.
  77. envStrs = []
  78. for (key, value) in env.items():
  79. envStrs.append('%s=%s' % (key, value))
  80. env = '\0'.join(envStrs) + '\0'
  81. if PY2:
  82. command = _unicode(command)
  83. cwd = _unicode(cwd)
  84. cmdline = _unicode(cmdline)
  85. env = _unicode(env)
  86. if len(argv) == 1:
  87. proc.spawn(command, cwd=cwd, env=env)
  88. else:
  89. proc.spawn(command, cwd=cwd, env=env, cmdline=cmdline)
  90. inst = cls(proc)
  91. inst._winsize = dimensions
  92. # Set some informational attributes
  93. inst.argv = argv
  94. if env is not None:
  95. inst.env = env
  96. if cwd is not None:
  97. inst.launch_dir = cwd
  98. return inst
  99. @property
  100. def exitstatus(self):
  101. """The exit status of the process.
  102. """
  103. return self.pty.exitstatus
  104. def fileno(self):
  105. """This returns the file descriptor of the pty for the child.
  106. """
  107. return self.fd
  108. def close(self, force=False):
  109. """This closes the connection with the child application. Note that
  110. calling close() more than once is valid. This emulates standard Python
  111. behavior with files. Set force to True if you want to make sure that
  112. the child is terminated (SIGKILL is sent if the child ignores
  113. SIGINT)."""
  114. if not self.closed:
  115. self.pty.close()
  116. self.fileobj.close()
  117. self._server.close()
  118. # Give kernel time to update process status.
  119. time.sleep(self.delayafterclose)
  120. if self.isalive():
  121. if not self.terminate(force):
  122. raise IOError('Could not terminate the child.')
  123. self.fd = -1
  124. self.closed = True
  125. del self.pty
  126. self.pty = None
  127. def __del__(self):
  128. """This makes sure that no system resources are left open. Python only
  129. garbage collects Python objects. OS file descriptors are not Python
  130. objects, so they must be handled explicitly. If the child file
  131. descriptor was opened outside of this class (passed to the constructor)
  132. then this does not close it.
  133. """
  134. # It is possible for __del__ methods to execute during the
  135. # teardown of the Python VM itself. Thus self.close() may
  136. # trigger an exception because os.close may be None.
  137. try:
  138. self.close()
  139. except Exception:
  140. pass
  141. def flush(self):
  142. """This does nothing. It is here to support the interface for a
  143. File-like object. """
  144. pass
  145. def isatty(self):
  146. """This returns True if the file descriptor is open and connected to a
  147. tty(-like) device, else False."""
  148. return self.isalive()
  149. def read(self, size=1024):
  150. """Read and return at most ``size`` characters from the pty.
  151. Can block if there is nothing to read. Raises :exc:`EOFError` if the
  152. terminal was closed.
  153. """
  154. data = self.fileobj.recv(size)
  155. if not data:
  156. self.flag_eof = True
  157. raise EOFError('Pty is closed')
  158. return self.decoder.decode(data, final=False)
  159. def readline(self):
  160. """Read one line from the pseudoterminal as bytes.
  161. Can block if there is nothing to read. Raises :exc:`EOFError` if the
  162. terminal was closed.
  163. """
  164. buf = []
  165. while 1:
  166. try:
  167. ch = self.read(1)
  168. except EOFError:
  169. return ''.join(buf)
  170. buf.append(ch)
  171. if ch == '\n':
  172. return ''.join(buf)
  173. def write(self, s):
  174. """Write the string ``s`` to the pseudoterminal.
  175. Returns the number of bytes written.
  176. """
  177. if not self.isalive():
  178. raise EOFError('Pty is closed')
  179. if PY2:
  180. s = _unicode(s)
  181. success, nbytes = self.pty.write(s)
  182. if not success:
  183. raise IOError('Write failed')
  184. return nbytes
  185. def terminate(self, force=False):
  186. """This forces a child process to terminate."""
  187. if not self.isalive():
  188. return True
  189. self.kill(signal.SIGINT)
  190. time.sleep(self.delayafterterminate)
  191. if not self.isalive():
  192. return True
  193. if force:
  194. self.kill(signal.SIGKILL)
  195. time.sleep(self.delayafterterminate)
  196. if not self.isalive():
  197. return True
  198. else:
  199. return False
  200. def wait(self):
  201. """This waits until the child exits. This is a blocking call. This will
  202. not read any data from the child.
  203. """
  204. while self.isalive():
  205. time.sleep(0.1)
  206. return self.exitstatus
  207. def isalive(self):
  208. """This tests if the child process is running or not. This is
  209. non-blocking. If the child was terminated then this will read the
  210. exitstatus or signalstatus of the child. This returns True if the child
  211. process appears to be running or False if not.
  212. """
  213. return self.pty and self.pty.isalive()
  214. def kill(self, sig=None):
  215. """Kill the process with the given signal.
  216. """
  217. os.kill(self.pid, sig)
  218. def sendcontrol(self, char):
  219. '''Helper method that wraps send() with mnemonic access for sending control
  220. character to the child (such as Ctrl-C or Ctrl-D). For example, to send
  221. Ctrl-G (ASCII 7, bell, '\a')::
  222. child.sendcontrol('g')
  223. See also, sendintr() and sendeof().
  224. '''
  225. char = char.lower()
  226. a = ord(char)
  227. if 97 <= a <= 122:
  228. a = a - ord('a') + 1
  229. byte = bytes([a])
  230. return self.pty.write(byte.decode('utf-8')), byte
  231. d = {'@': 0, '`': 0,
  232. '[': 27, '{': 27,
  233. '\\': 28, '|': 28,
  234. ']': 29, '}': 29,
  235. '^': 30, '~': 30,
  236. '_': 31,
  237. '?': 127}
  238. if char not in d:
  239. return 0, b''
  240. byte = bytes([d[char]])
  241. return self.pty.write(byte.decode('utf-8')), byte
  242. def sendeof(self):
  243. """This sends an EOF to the child. This sends a character which causes
  244. the pending parent output buffer to be sent to the waiting child
  245. program without waiting for end-of-line. If it is the first character
  246. of the line, the read() in the user program returns 0, which signifies
  247. end-of-file. This means to work as expected a sendeof() has to be
  248. called at the beginning of a line. This method does not send a newline.
  249. It is the responsibility of the caller to ensure the eof is sent at the
  250. beginning of a line."""
  251. # Send control character 4 (Ctrl-D)
  252. self.pty.write('\x04'), '\x04'
  253. def sendintr(self):
  254. """This sends a SIGINT to the child. It does not require
  255. the SIGINT to be the first character on a line. """
  256. # Send control character 3 (Ctrl-C)
  257. self.pty.write('\x03'), '\x03'
  258. def eof(self):
  259. """This returns True if the EOF exception was ever raised.
  260. """
  261. return self.flag_eof
  262. def getwinsize(self):
  263. """Return the window size of the pseudoterminal as a tuple (rows, cols).
  264. """
  265. return self._winsize
  266. def setwinsize(self, rows, cols):
  267. """Set the terminal window size of the child tty.
  268. """
  269. self._winsize = (rows, cols)
  270. self.pty.set_size(cols, rows)
  271. def _read_in_thread(address, pty, blocking):
  272. """Read data from the pty in a thread.
  273. """
  274. client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  275. client.connect(address)
  276. while 1:
  277. data = pty.read(4096, blocking=blocking)
  278. if not data and not pty.isalive():
  279. while not data and not pty.iseof():
  280. data += pty.read(4096, blocking=blocking)
  281. if not data:
  282. try:
  283. client.send(b'')
  284. except socket.error:
  285. pass
  286. break
  287. try:
  288. client.send(data)
  289. except socket.error:
  290. break
  291. client.close()
  292. def _unicode(s):
  293. """Ensure that a string is Unicode on Python 2.
  294. """
  295. if isinstance(s, unicode): # noqa E891
  296. return s
  297. return s.decode('utf-8')