PageRenderTime 63ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/subprocess.py

https://bitbucket.org/dac_io/pypy
Python | 1511 lines | 1306 code | 65 blank | 140 comment | 101 complexity | 92925f4e3d86b545a0285c2c6e436175 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # subprocess - Subprocesses with accessible I/O streams
  2. #
  3. # For more information about this module, see PEP 324.
  4. #
  5. # This module should remain compatible with Python 2.2, see PEP 291.
  6. #
  7. # Copyright (c) 2003-2005 by Peter Astrand <astrand@lysator.liu.se>
  8. #
  9. # Licensed to PSF under a Contributor Agreement.
  10. # See http://www.python.org/2.4/license for licensing details.
  11. r"""subprocess - Subprocesses with accessible I/O streams
  12. This module allows you to spawn processes, connect to their
  13. input/output/error pipes, and obtain their return codes. This module
  14. intends to replace several other, older modules and functions, like:
  15. os.system
  16. os.spawn*
  17. os.popen*
  18. popen2.*
  19. commands.*
  20. Information about how the subprocess module can be used to replace these
  21. modules and functions can be found below.
  22. Using the subprocess module
  23. ===========================
  24. This module defines one class called Popen:
  25. class Popen(args, bufsize=0, executable=None,
  26. stdin=None, stdout=None, stderr=None,
  27. preexec_fn=None, close_fds=False, shell=False,
  28. cwd=None, env=None, universal_newlines=False,
  29. startupinfo=None, creationflags=0):
  30. Arguments are:
  31. args should be a string, or a sequence of program arguments. The
  32. program to execute is normally the first item in the args sequence or
  33. string, but can be explicitly set by using the executable argument.
  34. On UNIX, with shell=False (default): In this case, the Popen class
  35. uses os.execvp() to execute the child program. args should normally
  36. be a sequence. A string will be treated as a sequence with the string
  37. as the only item (the program to execute).
  38. On UNIX, with shell=True: If args is a string, it specifies the
  39. command string to execute through the shell. If args is a sequence,
  40. the first item specifies the command string, and any additional items
  41. will be treated as additional shell arguments.
  42. On Windows: the Popen class uses CreateProcess() to execute the child
  43. program, which operates on strings. If args is a sequence, it will be
  44. converted to a string using the list2cmdline method. Please note that
  45. not all MS Windows applications interpret the command line the same
  46. way: The list2cmdline is designed for applications using the same
  47. rules as the MS C runtime.
  48. bufsize, if given, has the same meaning as the corresponding argument
  49. to the built-in open() function: 0 means unbuffered, 1 means line
  50. buffered, any other positive value means use a buffer of
  51. (approximately) that size. A negative bufsize means to use the system
  52. default, which usually means fully buffered. The default value for
  53. bufsize is 0 (unbuffered).
  54. stdin, stdout and stderr specify the executed programs' standard
  55. input, standard output and standard error file handles, respectively.
  56. Valid values are PIPE, an existing file descriptor (a positive
  57. integer), an existing file object, and None. PIPE indicates that a
  58. new pipe to the child should be created. With None, no redirection
  59. will occur; the child's file handles will be inherited from the
  60. parent. Additionally, stderr can be STDOUT, which indicates that the
  61. stderr data from the applications should be captured into the same
  62. file handle as for stdout.
  63. If preexec_fn is set to a callable object, this object will be called
  64. in the child process just before the child is executed.
  65. If close_fds is true, all file descriptors except 0, 1 and 2 will be
  66. closed before the child process is executed.
  67. if shell is true, the specified command will be executed through the
  68. shell.
  69. If cwd is not None, the current directory will be changed to cwd
  70. before the child is executed.
  71. If env is not None, it defines the environment variables for the new
  72. process.
  73. If universal_newlines is true, the file objects stdout and stderr are
  74. opened as a text files, but lines may be terminated by any of '\n',
  75. the Unix end-of-line convention, '\r', the Macintosh convention or
  76. '\r\n', the Windows convention. All of these external representations
  77. are seen as '\n' by the Python program. Note: This feature is only
  78. available if Python is built with universal newline support (the
  79. default). Also, the newlines attribute of the file objects stdout,
  80. stdin and stderr are not updated by the communicate() method.
  81. The startupinfo and creationflags, if given, will be passed to the
  82. underlying CreateProcess() function. They can specify things such as
  83. appearance of the main window and priority for the new process.
  84. (Windows only)
  85. This module also defines some shortcut functions:
  86. call(*popenargs, **kwargs):
  87. Run command with arguments. Wait for command to complete, then
  88. return the returncode attribute.
  89. The arguments are the same as for the Popen constructor. Example:
  90. retcode = call(["ls", "-l"])
  91. check_call(*popenargs, **kwargs):
  92. Run command with arguments. Wait for command to complete. If the
  93. exit code was zero then return, otherwise raise
  94. CalledProcessError. The CalledProcessError object will have the
  95. return code in the returncode attribute.
  96. The arguments are the same as for the Popen constructor. Example:
  97. check_call(["ls", "-l"])
  98. check_output(*popenargs, **kwargs):
  99. Run command with arguments and return its output as a byte string.
  100. If the exit code was non-zero it raises a CalledProcessError. The
  101. CalledProcessError object will have the return code in the returncode
  102. attribute and output in the output attribute.
  103. The arguments are the same as for the Popen constructor. Example:
  104. output = check_output(["ls", "-l", "/dev/null"])
  105. Exceptions
  106. ----------
  107. Exceptions raised in the child process, before the new program has
  108. started to execute, will be re-raised in the parent. Additionally,
  109. the exception object will have one extra attribute called
  110. 'child_traceback', which is a string containing traceback information
  111. from the childs point of view.
  112. The most common exception raised is OSError. This occurs, for
  113. example, when trying to execute a non-existent file. Applications
  114. should prepare for OSErrors.
  115. A ValueError will be raised if Popen is called with invalid arguments.
  116. check_call() and check_output() will raise CalledProcessError, if the
  117. called process returns a non-zero return code.
  118. Security
  119. --------
  120. Unlike some other popen functions, this implementation will never call
  121. /bin/sh implicitly. This means that all characters, including shell
  122. metacharacters, can safely be passed to child processes.
  123. Popen objects
  124. =============
  125. Instances of the Popen class have the following methods:
  126. poll()
  127. Check if child process has terminated. Returns returncode
  128. attribute.
  129. wait()
  130. Wait for child process to terminate. Returns returncode attribute.
  131. communicate(input=None)
  132. Interact with process: Send data to stdin. Read data from stdout
  133. and stderr, until end-of-file is reached. Wait for process to
  134. terminate. The optional input argument should be a string to be
  135. sent to the child process, or None, if no data should be sent to
  136. the child.
  137. communicate() returns a tuple (stdout, stderr).
  138. Note: The data read is buffered in memory, so do not use this
  139. method if the data size is large or unlimited.
  140. The following attributes are also available:
  141. stdin
  142. If the stdin argument is PIPE, this attribute is a file object
  143. that provides input to the child process. Otherwise, it is None.
  144. stdout
  145. If the stdout argument is PIPE, this attribute is a file object
  146. that provides output from the child process. Otherwise, it is
  147. None.
  148. stderr
  149. If the stderr argument is PIPE, this attribute is file object that
  150. provides error output from the child process. Otherwise, it is
  151. None.
  152. pid
  153. The process ID of the child process.
  154. returncode
  155. The child return code. A None value indicates that the process
  156. hasn't terminated yet. A negative value -N indicates that the
  157. child was terminated by signal N (UNIX only).
  158. Replacing older functions with the subprocess module
  159. ====================================================
  160. In this section, "a ==> b" means that b can be used as a replacement
  161. for a.
  162. Note: All functions in this section fail (more or less) silently if
  163. the executed program cannot be found; this module raises an OSError
  164. exception.
  165. In the following examples, we assume that the subprocess module is
  166. imported with "from subprocess import *".
  167. Replacing /bin/sh shell backquote
  168. ---------------------------------
  169. output=`mycmd myarg`
  170. ==>
  171. output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
  172. Replacing shell pipe line
  173. -------------------------
  174. output=`dmesg | grep hda`
  175. ==>
  176. p1 = Popen(["dmesg"], stdout=PIPE)
  177. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  178. output = p2.communicate()[0]
  179. Replacing os.system()
  180. ---------------------
  181. sts = os.system("mycmd" + " myarg")
  182. ==>
  183. p = Popen("mycmd" + " myarg", shell=True)
  184. pid, sts = os.waitpid(p.pid, 0)
  185. Note:
  186. * Calling the program through the shell is usually not required.
  187. * It's easier to look at the returncode attribute than the
  188. exitstatus.
  189. A more real-world example would look like this:
  190. try:
  191. retcode = call("mycmd" + " myarg", shell=True)
  192. if retcode < 0:
  193. print >>sys.stderr, "Child was terminated by signal", -retcode
  194. else:
  195. print >>sys.stderr, "Child returned", retcode
  196. except OSError, e:
  197. print >>sys.stderr, "Execution failed:", e
  198. Replacing os.spawn*
  199. -------------------
  200. P_NOWAIT example:
  201. pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
  202. ==>
  203. pid = Popen(["/bin/mycmd", "myarg"]).pid
  204. P_WAIT example:
  205. retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
  206. ==>
  207. retcode = call(["/bin/mycmd", "myarg"])
  208. Vector example:
  209. os.spawnvp(os.P_NOWAIT, path, args)
  210. ==>
  211. Popen([path] + args[1:])
  212. Environment example:
  213. os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
  214. ==>
  215. Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
  216. Replacing os.popen*
  217. -------------------
  218. pipe = os.popen("cmd", mode='r', bufsize)
  219. ==>
  220. pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
  221. pipe = os.popen("cmd", mode='w', bufsize)
  222. ==>
  223. pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
  224. (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
  225. ==>
  226. p = Popen("cmd", shell=True, bufsize=bufsize,
  227. stdin=PIPE, stdout=PIPE, close_fds=True)
  228. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  229. (child_stdin,
  230. child_stdout,
  231. child_stderr) = os.popen3("cmd", mode, bufsize)
  232. ==>
  233. p = Popen("cmd", shell=True, bufsize=bufsize,
  234. stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
  235. (child_stdin,
  236. child_stdout,
  237. child_stderr) = (p.stdin, p.stdout, p.stderr)
  238. (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
  239. bufsize)
  240. ==>
  241. p = Popen("cmd", shell=True, bufsize=bufsize,
  242. stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  243. (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
  244. On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
  245. the command to execute, in which case arguments will be passed
  246. directly to the program without shell intervention. This usage can be
  247. replaced as follows:
  248. (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
  249. bufsize)
  250. ==>
  251. p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
  252. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  253. Return code handling translates as follows:
  254. pipe = os.popen("cmd", 'w')
  255. ...
  256. rc = pipe.close()
  257. if rc is not None and rc % 256:
  258. print "There were some errors"
  259. ==>
  260. process = Popen("cmd", 'w', shell=True, stdin=PIPE)
  261. ...
  262. process.stdin.close()
  263. if process.wait() != 0:
  264. print "There were some errors"
  265. Replacing popen2.*
  266. ------------------
  267. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
  268. ==>
  269. p = Popen(["somestring"], shell=True, bufsize=bufsize
  270. stdin=PIPE, stdout=PIPE, close_fds=True)
  271. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  272. On Unix, popen2 also accepts a sequence as the command to execute, in
  273. which case arguments will be passed directly to the program without
  274. shell intervention. This usage can be replaced as follows:
  275. (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
  276. mode)
  277. ==>
  278. p = Popen(["mycmd", "myarg"], bufsize=bufsize,
  279. stdin=PIPE, stdout=PIPE, close_fds=True)
  280. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  281. The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
  282. except that:
  283. * subprocess.Popen raises an exception if the execution fails
  284. * the capturestderr argument is replaced with the stderr argument.
  285. * stdin=PIPE and stdout=PIPE must be specified.
  286. * popen2 closes all filedescriptors by default, but you have to specify
  287. close_fds=True with subprocess.Popen.
  288. """
  289. import sys
  290. mswindows = (sys.platform == "win32")
  291. import os
  292. import types
  293. import traceback
  294. import gc
  295. import signal
  296. import errno
  297. # Exception classes used by this module.
  298. class CalledProcessError(Exception):
  299. """This exception is raised when a process run by check_call() or
  300. check_output() returns a non-zero exit status.
  301. The exit status will be stored in the returncode attribute;
  302. check_output() will also store the output in the output attribute.
  303. """
  304. def __init__(self, returncode, cmd, output=None):
  305. self.returncode = returncode
  306. self.cmd = cmd
  307. self.output = output
  308. def __str__(self):
  309. return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  310. if mswindows:
  311. import threading
  312. import msvcrt
  313. import _subprocess
  314. class STARTUPINFO:
  315. dwFlags = 0
  316. hStdInput = None
  317. hStdOutput = None
  318. hStdError = None
  319. wShowWindow = 0
  320. class pywintypes:
  321. error = IOError
  322. else:
  323. import select
  324. _has_poll = hasattr(select, 'poll')
  325. import fcntl
  326. import pickle
  327. # When select or poll has indicated that the file is writable,
  328. # we can write up to _PIPE_BUF bytes without risk of blocking.
  329. # POSIX defines PIPE_BUF as >= 512.
  330. _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
  331. __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call",
  332. "check_output", "CalledProcessError"]
  333. if mswindows:
  334. from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
  335. STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
  336. STD_ERROR_HANDLE, SW_HIDE,
  337. STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
  338. __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
  339. "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
  340. "STD_ERROR_HANDLE", "SW_HIDE",
  341. "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
  342. try:
  343. MAXFD = os.sysconf("SC_OPEN_MAX")
  344. except:
  345. MAXFD = 256
  346. _active = []
  347. def _cleanup():
  348. for inst in _active[:]:
  349. res = inst._internal_poll(_deadstate=sys.maxint)
  350. if res is not None and res >= 0:
  351. try:
  352. _active.remove(inst)
  353. except ValueError:
  354. # This can happen if two threads create a new Popen instance.
  355. # It's harmless that it was already removed, so ignore.
  356. pass
  357. PIPE = -1
  358. STDOUT = -2
  359. def _eintr_retry_call(func, *args):
  360. while True:
  361. try:
  362. return func(*args)
  363. except OSError, e:
  364. if e.errno == errno.EINTR:
  365. continue
  366. raise
  367. def call(*popenargs, **kwargs):
  368. """Run command with arguments. Wait for command to complete, then
  369. return the returncode attribute.
  370. The arguments are the same as for the Popen constructor. Example:
  371. retcode = call(["ls", "-l"])
  372. """
  373. return Popen(*popenargs, **kwargs).wait()
  374. def check_call(*popenargs, **kwargs):
  375. """Run command with arguments. Wait for command to complete. If
  376. the exit code was zero then return, otherwise raise
  377. CalledProcessError. The CalledProcessError object will have the
  378. return code in the returncode attribute.
  379. The arguments are the same as for the Popen constructor. Example:
  380. check_call(["ls", "-l"])
  381. """
  382. retcode = call(*popenargs, **kwargs)
  383. if retcode:
  384. cmd = kwargs.get("args")
  385. if cmd is None:
  386. cmd = popenargs[0]
  387. raise CalledProcessError(retcode, cmd)
  388. return 0
  389. def check_output(*popenargs, **kwargs):
  390. r"""Run command with arguments and return its output as a byte string.
  391. If the exit code was non-zero it raises a CalledProcessError. The
  392. CalledProcessError object will have the return code in the returncode
  393. attribute and output in the output attribute.
  394. The arguments are the same as for the Popen constructor. Example:
  395. >>> check_output(["ls", "-l", "/dev/null"])
  396. 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
  397. The stdout argument is not allowed as it is used internally.
  398. To capture standard error in the result, use stderr=STDOUT.
  399. >>> check_output(["/bin/sh", "-c",
  400. ... "ls -l non_existent_file ; exit 0"],
  401. ... stderr=STDOUT)
  402. 'ls: non_existent_file: No such file or directory\n'
  403. """
  404. if 'stdout' in kwargs:
  405. raise ValueError('stdout argument not allowed, it will be overridden.')
  406. process = Popen(stdout=PIPE, *popenargs, **kwargs)
  407. output, unused_err = process.communicate()
  408. retcode = process.poll()
  409. if retcode:
  410. cmd = kwargs.get("args")
  411. if cmd is None:
  412. cmd = popenargs[0]
  413. raise CalledProcessError(retcode, cmd, output=output)
  414. return output
  415. def list2cmdline(seq):
  416. """
  417. Translate a sequence of arguments into a command line
  418. string, using the same rules as the MS C runtime:
  419. 1) Arguments are delimited by white space, which is either a
  420. space or a tab.
  421. 2) A string surrounded by double quotation marks is
  422. interpreted as a single argument, regardless of white space
  423. contained within. A quoted string can be embedded in an
  424. argument.
  425. 3) A double quotation mark preceded by a backslash is
  426. interpreted as a literal double quotation mark.
  427. 4) Backslashes are interpreted literally, unless they
  428. immediately precede a double quotation mark.
  429. 5) If backslashes immediately precede a double quotation mark,
  430. every pair of backslashes is interpreted as a literal
  431. backslash. If the number of backslashes is odd, the last
  432. backslash escapes the next double quotation mark as
  433. described in rule 3.
  434. """
  435. # See
  436. # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
  437. # or search http://msdn.microsoft.com for
  438. # "Parsing C++ Command-Line Arguments"
  439. result = []
  440. needquote = False
  441. for arg in seq:
  442. bs_buf = []
  443. # Add a space to separate this argument from the others
  444. if result:
  445. result.append(' ')
  446. needquote = (" " in arg) or ("\t" in arg) or not arg
  447. if needquote:
  448. result.append('"')
  449. for c in arg:
  450. if c == '\\':
  451. # Don't know if we need to double yet.
  452. bs_buf.append(c)
  453. elif c == '"':
  454. # Double backslashes.
  455. result.append('\\' * len(bs_buf)*2)
  456. bs_buf = []
  457. result.append('\\"')
  458. else:
  459. # Normal char
  460. if bs_buf:
  461. result.extend(bs_buf)
  462. bs_buf = []
  463. result.append(c)
  464. # Add remaining backslashes, if any.
  465. if bs_buf:
  466. result.extend(bs_buf)
  467. if needquote:
  468. result.extend(bs_buf)
  469. result.append('"')
  470. return ''.join(result)
  471. class Popen(object):
  472. def __init__(self, args, bufsize=0, executable=None,
  473. stdin=None, stdout=None, stderr=None,
  474. preexec_fn=None, close_fds=False, shell=False,
  475. cwd=None, env=None, universal_newlines=False,
  476. startupinfo=None, creationflags=0):
  477. """Create new Popen instance."""
  478. _cleanup()
  479. self._child_created = False
  480. if not isinstance(bufsize, (int, long)):
  481. raise TypeError("bufsize must be an integer")
  482. if mswindows:
  483. if preexec_fn is not None:
  484. raise ValueError("preexec_fn is not supported on Windows "
  485. "platforms")
  486. if close_fds and (stdin is not None or stdout is not None or
  487. stderr is not None):
  488. raise ValueError("close_fds is not supported on Windows "
  489. "platforms if you redirect stdin/stdout/stderr")
  490. else:
  491. # POSIX
  492. if startupinfo is not None:
  493. raise ValueError("startupinfo is only supported on Windows "
  494. "platforms")
  495. if creationflags != 0:
  496. raise ValueError("creationflags is only supported on Windows "
  497. "platforms")
  498. self.stdin = None
  499. self.stdout = None
  500. self.stderr = None
  501. self.pid = None
  502. self.returncode = None
  503. self.universal_newlines = universal_newlines
  504. # Input and output objects. The general principle is like
  505. # this:
  506. #
  507. # Parent Child
  508. # ------ -----
  509. # p2cwrite ---stdin---> p2cread
  510. # c2pread <--stdout--- c2pwrite
  511. # errread <--stderr--- errwrite
  512. #
  513. # On POSIX, the child objects are file descriptors. On
  514. # Windows, these are Windows file handles. The parent objects
  515. # are file descriptors on both platforms. The parent objects
  516. # are None when not using PIPEs. The child objects are None
  517. # when not redirecting.
  518. (p2cread, p2cwrite,
  519. c2pread, c2pwrite,
  520. errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  521. self._execute_child(args, executable, preexec_fn, close_fds,
  522. cwd, env, universal_newlines,
  523. startupinfo, creationflags, shell,
  524. p2cread, p2cwrite,
  525. c2pread, c2pwrite,
  526. errread, errwrite)
  527. if mswindows:
  528. if p2cwrite is not None:
  529. p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
  530. if c2pread is not None:
  531. c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
  532. if errread is not None:
  533. errread = msvcrt.open_osfhandle(errread.Detach(), 0)
  534. if p2cwrite is not None:
  535. self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
  536. if c2pread is not None:
  537. if universal_newlines:
  538. self.stdout = os.fdopen(c2pread, 'rU', bufsize)
  539. else:
  540. self.stdout = os.fdopen(c2pread, 'rb', bufsize)
  541. if errread is not None:
  542. if universal_newlines:
  543. self.stderr = os.fdopen(errread, 'rU', bufsize)
  544. else:
  545. self.stderr = os.fdopen(errread, 'rb', bufsize)
  546. def _translate_newlines(self, data):
  547. data = data.replace("\r\n", "\n")
  548. data = data.replace("\r", "\n")
  549. return data
  550. def __del__(self, _maxint=sys.maxint, _active=_active):
  551. if not self._child_created:
  552. # We didn't get to successfully create a child process.
  553. return
  554. # In case the child hasn't been waited on, check if it's done.
  555. self._internal_poll(_deadstate=_maxint)
  556. if self.returncode is None and _active is not None:
  557. # Child is still running, keep us alive until we can wait on it.
  558. _active.append(self)
  559. def communicate(self, input=None):
  560. """Interact with process: Send data to stdin. Read data from
  561. stdout and stderr, until end-of-file is reached. Wait for
  562. process to terminate. The optional input argument should be a
  563. string to be sent to the child process, or None, if no data
  564. should be sent to the child.
  565. communicate() returns a tuple (stdout, stderr)."""
  566. # Optimization: If we are only using one pipe, or no pipe at
  567. # all, using select() or threads is unnecessary.
  568. if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
  569. stdout = None
  570. stderr = None
  571. if self.stdin:
  572. if input:
  573. try:
  574. self.stdin.write(input)
  575. except IOError as e:
  576. if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
  577. raise
  578. self.stdin.close()
  579. elif self.stdout:
  580. stdout = self.stdout.read()
  581. self.stdout.close()
  582. elif self.stderr:
  583. stderr = self.stderr.read()
  584. self.stderr.close()
  585. self.wait()
  586. return (stdout, stderr)
  587. return self._communicate(input)
  588. def poll(self):
  589. return self._internal_poll()
  590. if mswindows:
  591. #
  592. # Windows methods
  593. #
  594. def _get_handles(self, stdin, stdout, stderr):
  595. """Construct and return tuple with IO objects:
  596. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  597. """
  598. if stdin is None and stdout is None and stderr is None:
  599. return (None, None, None, None, None, None)
  600. p2cread, p2cwrite = None, None
  601. c2pread, c2pwrite = None, None
  602. errread, errwrite = None, None
  603. if stdin is None:
  604. p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
  605. if p2cread is None:
  606. p2cread, _ = _subprocess.CreatePipe(None, 0)
  607. elif stdin == PIPE:
  608. p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
  609. elif isinstance(stdin, int):
  610. p2cread = msvcrt.get_osfhandle(stdin)
  611. else:
  612. # Assuming file-like object
  613. p2cread = msvcrt.get_osfhandle(stdin.fileno())
  614. p2cread = self._make_inheritable(p2cread)
  615. if stdout is None:
  616. c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
  617. if c2pwrite is None:
  618. _, c2pwrite = _subprocess.CreatePipe(None, 0)
  619. elif stdout == PIPE:
  620. c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
  621. elif isinstance(stdout, int):
  622. c2pwrite = msvcrt.get_osfhandle(stdout)
  623. else:
  624. # Assuming file-like object
  625. c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  626. c2pwrite = self._make_inheritable(c2pwrite)
  627. if stderr is None:
  628. errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
  629. if errwrite is None:
  630. _, errwrite = _subprocess.CreatePipe(None, 0)
  631. elif stderr == PIPE:
  632. errread, errwrite = _subprocess.CreatePipe(None, 0)
  633. elif stderr == STDOUT:
  634. errwrite = c2pwrite
  635. elif isinstance(stderr, int):
  636. errwrite = msvcrt.get_osfhandle(stderr)
  637. else:
  638. # Assuming file-like object
  639. errwrite = msvcrt.get_osfhandle(stderr.fileno())
  640. errwrite = self._make_inheritable(errwrite)
  641. return (p2cread, p2cwrite,
  642. c2pread, c2pwrite,
  643. errread, errwrite)
  644. def _make_inheritable(self, handle):
  645. """Return a duplicate of handle, which is inheritable"""
  646. return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
  647. handle, _subprocess.GetCurrentProcess(), 0, 1,
  648. _subprocess.DUPLICATE_SAME_ACCESS)
  649. def _find_w9xpopen(self):
  650. """Find and return absolut path to w9xpopen.exe"""
  651. w9xpopen = os.path.join(
  652. os.path.dirname(_subprocess.GetModuleFileName(0)),
  653. "w9xpopen.exe")
  654. if not os.path.exists(w9xpopen):
  655. # Eeek - file-not-found - possibly an embedding
  656. # situation - see if we can locate it in sys.exec_prefix
  657. w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
  658. "w9xpopen.exe")
  659. if not os.path.exists(w9xpopen):
  660. raise RuntimeError("Cannot locate w9xpopen.exe, which is "
  661. "needed for Popen to work with your "
  662. "shell or platform.")
  663. return w9xpopen
  664. def _execute_child(self, args, executable, preexec_fn, close_fds,
  665. cwd, env, universal_newlines,
  666. startupinfo, creationflags, shell,
  667. p2cread, p2cwrite,
  668. c2pread, c2pwrite,
  669. errread, errwrite):
  670. """Execute program (MS Windows version)"""
  671. if not isinstance(args, types.StringTypes):
  672. args = list2cmdline(args)
  673. # Process startup details
  674. if startupinfo is None:
  675. startupinfo = STARTUPINFO()
  676. if None not in (p2cread, c2pwrite, errwrite):
  677. startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
  678. startupinfo.hStdInput = p2cread
  679. startupinfo.hStdOutput = c2pwrite
  680. startupinfo.hStdError = errwrite
  681. if shell:
  682. startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
  683. startupinfo.wShowWindow = _subprocess.SW_HIDE
  684. comspec = os.environ.get("COMSPEC", "cmd.exe")
  685. args = '{} /c "{}"'.format (comspec, args)
  686. if (_subprocess.GetVersion() >= 0x80000000 or
  687. os.path.basename(comspec).lower() == "command.com"):
  688. # Win9x, or using command.com on NT. We need to
  689. # use the w9xpopen intermediate program. For more
  690. # information, see KB Q150956
  691. # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
  692. w9xpopen = self._find_w9xpopen()
  693. args = '"%s" %s' % (w9xpopen, args)
  694. # Not passing CREATE_NEW_CONSOLE has been known to
  695. # cause random failures on win9x. Specifically a
  696. # dialog: "Your program accessed mem currently in
  697. # use at xxx" and a hopeful warning about the
  698. # stability of your system. Cost is Ctrl+C wont
  699. # kill children.
  700. creationflags |= _subprocess.CREATE_NEW_CONSOLE
  701. # Start the process
  702. try:
  703. hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
  704. # no special security
  705. None, None,
  706. int(not close_fds),
  707. creationflags,
  708. env,
  709. cwd,
  710. startupinfo)
  711. except pywintypes.error, e:
  712. # Translate pywintypes.error to WindowsError, which is
  713. # a subclass of OSError. FIXME: We should really
  714. # translate errno using _sys_errlist (or similar), but
  715. # how can this be done from Python?
  716. raise WindowsError(*e.args)
  717. finally:
  718. # Child is launched. Close the parent's copy of those pipe
  719. # handles that only the child should have open. You need
  720. # to make sure that no handles to the write end of the
  721. # output pipe are maintained in this process or else the
  722. # pipe will not close when the child process exits and the
  723. # ReadFile will hang.
  724. if p2cread is not None:
  725. p2cread.Close()
  726. if c2pwrite is not None:
  727. c2pwrite.Close()
  728. if errwrite is not None:
  729. errwrite.Close()
  730. # Retain the process handle, but close the thread handle
  731. self._child_created = True
  732. self._handle = hp
  733. self.pid = pid
  734. ht.Close()
  735. def _internal_poll(self, _deadstate=None,
  736. _WaitForSingleObject=_subprocess.WaitForSingleObject,
  737. _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
  738. _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
  739. """Check if child process has terminated. Returns returncode
  740. attribute.
  741. This method is called by __del__, so it can only refer to objects
  742. in its local scope.
  743. """
  744. if self.returncode is None:
  745. if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
  746. self.returncode = _GetExitCodeProcess(self._handle)
  747. return self.returncode
  748. def wait(self):
  749. """Wait for child process to terminate. Returns returncode
  750. attribute."""
  751. if self.returncode is None:
  752. _subprocess.WaitForSingleObject(self._handle,
  753. _subprocess.INFINITE)
  754. self.returncode = _subprocess.GetExitCodeProcess(self._handle)
  755. return self.returncode
  756. def _readerthread(self, fh, buffer):
  757. buffer.append(fh.read())
  758. def _communicate(self, input):
  759. stdout = None # Return
  760. stderr = None # Return
  761. if self.stdout:
  762. stdout = []
  763. stdout_thread = threading.Thread(target=self._readerthread,
  764. args=(self.stdout, stdout))
  765. stdout_thread.setDaemon(True)
  766. stdout_thread.start()
  767. if self.stderr:
  768. stderr = []
  769. stderr_thread = threading.Thread(target=self._readerthread,
  770. args=(self.stderr, stderr))
  771. stderr_thread.setDaemon(True)
  772. stderr_thread.start()
  773. if self.stdin:
  774. if input is not None:
  775. try:
  776. self.stdin.write(input)
  777. except IOError as e:
  778. if e.errno != errno.EPIPE:
  779. raise
  780. self.stdin.close()
  781. if self.stdout:
  782. stdout_thread.join()
  783. if self.stderr:
  784. stderr_thread.join()
  785. # All data exchanged. Translate lists into strings.
  786. if stdout is not None:
  787. stdout = stdout[0]
  788. if stderr is not None:
  789. stderr = stderr[0]
  790. # Translate newlines, if requested. We cannot let the file
  791. # object do the translation: It is based on stdio, which is
  792. # impossible to combine with select (unless forcing no
  793. # buffering).
  794. if self.universal_newlines and hasattr(file, 'newlines'):
  795. if stdout:
  796. stdout = self._translate_newlines(stdout)
  797. if stderr:
  798. stderr = self._translate_newlines(stderr)
  799. self.wait()
  800. return (stdout, stderr)
  801. def send_signal(self, sig):
  802. """Send a signal to the process
  803. """
  804. if sig == signal.SIGTERM:
  805. self.terminate()
  806. elif sig == signal.CTRL_C_EVENT:
  807. os.kill(self.pid, signal.CTRL_C_EVENT)
  808. elif sig == signal.CTRL_BREAK_EVENT:
  809. os.kill(self.pid, signal.CTRL_BREAK_EVENT)
  810. else:
  811. raise ValueError("Unsupported signal: {}".format(sig))
  812. def terminate(self):
  813. """Terminates the process
  814. """
  815. _subprocess.TerminateProcess(self._handle, 1)
  816. kill = terminate
  817. else:
  818. #
  819. # POSIX methods
  820. #
  821. def _get_handles(self, stdin, stdout, stderr):
  822. """Construct and return tuple with IO objects:
  823. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  824. """
  825. p2cread, p2cwrite = None, None
  826. c2pread, c2pwrite = None, None
  827. errread, errwrite = None, None
  828. if stdin is None:
  829. pass
  830. elif stdin == PIPE:
  831. p2cread, p2cwrite = os.pipe()
  832. elif isinstance(stdin, int):
  833. p2cread = stdin
  834. else:
  835. # Assuming file-like object
  836. p2cread = stdin.fileno()
  837. if stdout is None:
  838. pass
  839. elif stdout == PIPE:
  840. c2pread, c2pwrite = os.pipe()
  841. elif isinstance(stdout, int):
  842. c2pwrite = stdout
  843. else:
  844. # Assuming file-like object
  845. c2pwrite = stdout.fileno()
  846. if stderr is None:
  847. pass
  848. elif stderr == PIPE:
  849. errread, errwrite = os.pipe()
  850. elif stderr == STDOUT:
  851. errwrite = c2pwrite
  852. elif isinstance(stderr, int):
  853. errwrite = stderr
  854. else:
  855. # Assuming file-like object
  856. errwrite = stderr.fileno()
  857. return (p2cread, p2cwrite,
  858. c2pread, c2pwrite,
  859. errread, errwrite)
  860. def _set_cloexec_flag(self, fd, cloexec=True):
  861. try:
  862. cloexec_flag = fcntl.FD_CLOEXEC
  863. except AttributeError:
  864. cloexec_flag = 1
  865. old = fcntl.fcntl(fd, fcntl.F_GETFD)
  866. if cloexec:
  867. fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  868. else:
  869. fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
  870. def _close_fds(self, but):
  871. if hasattr(os, 'closerange'):
  872. os.closerange(3, but)
  873. os.closerange(but + 1, MAXFD)
  874. else:
  875. for i in xrange(3, MAXFD):
  876. if i == but:
  877. continue
  878. try:
  879. os.close(i)
  880. except:
  881. pass
  882. def _execute_child(self, args, executable, preexec_fn, close_fds,
  883. cwd, env, universal_newlines,
  884. startupinfo, creationflags, shell,
  885. p2cread, p2cwrite,
  886. c2pread, c2pwrite,
  887. errread, errwrite):
  888. """Execute program (POSIX version)"""
  889. if isinstance(args, types.StringTypes):
  890. args = [args]
  891. else:
  892. args = list(args)
  893. if shell:
  894. args = ["/bin/sh", "-c"] + args
  895. if executable:
  896. args[0] = executable
  897. if executable is None:
  898. executable = args[0]
  899. # For transferring possible exec failure from child to parent
  900. # The first char specifies the exception type: 0 means
  901. # OSError, 1 means some other error.
  902. errpipe_read, errpipe_write = os.pipe()
  903. try:
  904. try:
  905. self._set_cloexec_flag(errpipe_write)
  906. gc_was_enabled = gc.isenabled()
  907. # Disable gc to avoid bug where gc -> file_dealloc ->
  908. # write to stderr -> hang. http://bugs.python.org/issue1336
  909. gc.disable()
  910. try:
  911. self.pid = os.fork()
  912. except:
  913. if gc_was_enabled:
  914. gc.enable()
  915. raise
  916. self._child_created = True
  917. if self.pid == 0:
  918. # Child
  919. try:
  920. # Close parent's pipe ends
  921. if p2cwrite is not None:
  922. os.close(p2cwrite)
  923. if c2pread is not None:
  924. os.close(c2pread)
  925. if errread is not None:
  926. os.close(errread)
  927. os.close(errpipe_read)
  928. # Dup fds for child
  929. def _dup2(a, b):
  930. # dup2() removes the CLOEXEC flag but
  931. # we must do it ourselves if dup2()
  932. # would be a no-op (issue #10806).
  933. if a == b:
  934. self._set_cloexec_flag(a, False)
  935. elif a is not None:
  936. os.dup2(a, b)
  937. _dup2(p2cread, 0)
  938. _dup2(c2pwrite, 1)
  939. _dup2(errwrite, 2)
  940. # Close pipe fds. Make sure we don't close the
  941. # same fd more than once, or standard fds.
  942. closed = { None }
  943. for fd in [p2cread, c2pwrite, errwrite]:
  944. if fd not in closed and fd > 2:
  945. os.close(fd)
  946. closed.add(fd)
  947. # Close all other fds, if asked for
  948. if close_fds:
  949. self._close_fds(but=errpipe_write)
  950. if cwd is not None:
  951. os.chdir(cwd)
  952. if preexec_fn:
  953. preexec_fn()
  954. if env is None:
  955. os.execvp(executable, args)
  956. else:
  957. os.execvpe(executable, args, env)
  958. except:
  959. exc_type, exc_value, tb = sys.exc_info()
  960. # Save the traceback and attach it to the exception object
  961. exc_lines = traceback.format_exception(exc_type,
  962. exc_value,
  963. tb)
  964. exc_value.child_traceback = ''.join(exc_lines)
  965. os.write(errpipe_write, pickle.dumps(exc_value))
  966. # This exitcode won't be reported to applications, so it
  967. # really doesn't matter what we return.
  968. os._exit(255)
  969. # Parent
  970. if gc_was_enabled:
  971. gc.enable()
  972. finally:
  973. # be sure the FD is closed no matter what
  974. os.close(errpipe_write)
  975. if p2cread is not None and p2cwrite is not None:
  976. os.close(p2cread)
  977. if c2pwrite is not None and c2pread is not None:
  978. os.close(c2pwrite)
  979. if errwrite is not None and errread is not None:
  980. os.close(errwrite)
  981. # Wait for exec to fail or succeed; possibly raising exception
  982. # Exception limited to 1M
  983. data = _eintr_retry_call(os.read, errpipe_read, 1048576)
  984. finally:
  985. # be sure the FD is closed no matter what
  986. os.close(errpipe_read)
  987. if data != "":
  988. try:
  989. _eintr_retry_call(os.waitpid, self.pid, 0)
  990. except OSError as e:
  991. if e.errno != errno.ECHILD:
  992. raise
  993. child_exception = pickle.loads(data)
  994. for fd in (p2cwrite, c2pread, errread):
  995. if fd is not None:
  996. os.close(fd)
  997. raise child_exception
  998. def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
  999. _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
  1000. _WEXITSTATUS=os.WEXITSTATUS):
  1001. # This method is called (indirectly) by __del__, so it cannot
  1002. # refer to anything outside of its local scope."""
  1003. if _WIFSIGNALED(sts):
  1004. self.returncode = -_WTERMSIG(sts)
  1005. elif _WIFEXITED(sts):
  1006. self.returncode = _WEXITSTATUS(sts)
  1007. else:
  1008. # Should never happen
  1009. raise RuntimeError("Unknown child exit status!")
  1010. def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
  1011. _WNOHANG=os.WNOHANG, _os_error=os.error):
  1012. """Check if child process has terminated. Returns returncode
  1013. attribute.
  1014. This method is called by __del__, so it cannot reference anything
  1015. outside of the local scope (nor can any methods it calls).
  1016. """
  1017. if self.returncode is None:
  1018. try:
  1019. pid, sts = _waitpid(self.pid, _WNOHANG)
  1020. if pid == self.pid:
  1021. self._handle_exitstatus(sts)
  1022. except _os_error:
  1023. if _deadstate is not None:
  1024. self.returncode = _deadstate
  1025. return self.returncode
  1026. def wait(self):
  1027. """Wait for child process to terminate. Returns returncode
  1028. attribute."""
  1029. if self.returncode is None:
  1030. try:
  1031. pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
  1032. except OSError as e:
  1033. if e.errno != errno.ECHILD:
  1034. raise
  1035. # This happens if SIGCLD is set to be ignored or waiting
  1036. # for child processes has otherwise been disabled for our
  1037. # process. This child is dead, we can't get the status.
  1038. sts = 0
  1039. self._handle_exitstatus(sts)
  1040. return self.returncode
  1041. def _communicate(self, input):
  1042. if self.stdin:
  1043. # Flush stdio buffer. This might block, if the user has
  1044. # been writing to .stdin in an uncontrolled fashion.
  1045. self.stdin.flush()
  1046. if not input:
  1047. self.stdin.close()
  1048. if _has_poll:
  1049. stdout, stderr = self._communicate_with_poll(input)
  1050. else:
  1051. stdout, stderr = self._communicate_with_select(input)
  1052. # All data exchanged. Translate lists into strings.
  1053. if stdout is not None:
  1054. stdout = ''.join(stdout)
  1055. if stderr is not None:
  1056. stderr = ''.join(stderr)
  1057. # Translate newlines, if requested. We cannot let the file
  1058. # object do the translation: It is based on stdio, which is
  1059. # impossible to combine with select (unless forcing no
  1060. # buffering).
  1061. if self.universal_newlines and hasattr(file, 'newlines'):
  1062. if stdout:
  1063. stdout = self._translate_newlines(stdout)
  1064. if stderr:
  1065. stderr = self._translate_newlines(stderr)
  1066. self.wait()
  1067. return (stdout, stderr)
  1068. def _communicate_with_poll(self, input):
  1069. stdout = None # Return
  1070. stderr = None # Return
  1071. fd2file = {}
  1072. fd2output = {}
  1073. poller = select.poll()
  1074. def register_and_append(file_obj, eventmask):
  1075. poller.register(file_obj.fileno(), eventmask)
  1076. fd2file[file_obj.fileno()] = file_obj
  1077. def close_unregister_and_remove(fd):
  1078. poller.unregister(fd)
  1079. fd2file[fd].close()
  1080. fd2file.pop(fd)
  1081. if self.stdin and input:
  1082. register_and_append(self.stdin, select.POLLOUT)
  1083. select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
  1084. if self.stdout:
  1085. register_and_append(self.stdout, select_POLLIN_POLLPRI)
  1086. fd2output[self.stdout.fileno()] = stdout = []
  1087. if self.stderr:
  1088. register_and_append(self.stderr, select_POLLIN_POLLPRI)
  1089. fd2output[self.stderr.fileno()] = stderr = []
  1090. input_offset = 0
  1091. while fd2file:
  1092. try:
  1093. ready = poller.poll()
  1094. except select.error, e:
  1095. if e.args[0] == errno.EINTR:
  1096. continue
  1097. raise
  1098. for fd, mode in ready:
  1099. if mode & select.POLLOUT:
  1100. chunk = input[input_offset : input_offset + _PIPE_BUF]
  1101. try:
  1102. input_offset += os.write(fd, chunk)
  1103. except OSError as e:
  1104. if e.errno == errno.EPIPE:
  1105. close_unregister_and_remove(fd)
  1106. else:
  1107. raise
  1108. else:
  1109. if input_offset >= len(input):
  1110. close_unregister_and_remove(fd)
  1111. elif mode & select_POLLIN_POLLP

Large files files are truncated, but you can click here to view the full file