PageRenderTime 78ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/lib-python/2.7/subprocess.py

https://bitbucket.org/nbtaylor/pypy
Python | 1536 lines | 1321 code | 67 blank | 148 comment | 104 complexity | a32909973199f2f2e4d7217e5c17db61 MD5 | raw 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:
  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, IOError) as 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 __init__ hasn't had a chance to execute (e.g. if it
  552. # was passed an undeclared keyword argument), we don't
  553. # have a _child_created attribute at all.
  554. if not getattr(self, '_child_created', False):
  555. # We didn't get to successfully create a child process.
  556. return
  557. # In case the child hasn't been waited on, check if it's done.
  558. self._internal_poll(_deadstate=_maxint)
  559. if self.returncode is None and _active is not None:
  560. # Child is still running, keep us alive until we can wait on it.
  561. _active.append(self)
  562. def communicate(self, input=None):
  563. """Interact with process: Send data to stdin. Read data from
  564. stdout and stderr, until end-of-file is reached. Wait for
  565. process to terminate. The optional input argument should be a
  566. string to be sent to the child process, or None, if no data
  567. should be sent to the child.
  568. communicate() returns a tuple (stdout, stderr)."""
  569. # Optimization: If we are only using one pipe, or no pipe at
  570. # all, using select() or threads is unnecessary.
  571. if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
  572. stdout = None
  573. stderr = None
  574. if self.stdin:
  575. if input:
  576. try:
  577. self.stdin.write(input)
  578. except IOError as e:
  579. if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
  580. raise
  581. self.stdin.close()
  582. elif self.stdout:
  583. stdout = _eintr_retry_call(self.stdout.read)
  584. self.stdout.close()
  585. elif self.stderr:
  586. stderr = _eintr_retry_call(self.stderr.read)
  587. self.stderr.close()
  588. self.wait()
  589. return (stdout, stderr)
  590. return self._communicate(input)
  591. def poll(self):
  592. return self._internal_poll()
  593. if mswindows:
  594. #
  595. # Windows methods
  596. #
  597. def _get_handles(self, stdin, stdout, stderr):
  598. """Construct and return tuple with IO objects:
  599. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  600. """
  601. if stdin is None and stdout is None and stderr is None:
  602. return (None, None, None, None, None, None)
  603. p2cread, p2cwrite = None, None
  604. c2pread, c2pwrite = None, None
  605. errread, errwrite = None, None
  606. if stdin is None:
  607. p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
  608. if p2cread is None:
  609. p2cread, _ = _subprocess.CreatePipe(None, 0)
  610. elif stdin == PIPE:
  611. p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
  612. elif isinstance(stdin, int):
  613. p2cread = msvcrt.get_osfhandle(stdin)
  614. else:
  615. # Assuming file-like object
  616. p2cread = msvcrt.get_osfhandle(stdin.fileno())
  617. p2cread = self._make_inheritable(p2cread)
  618. if stdout is None:
  619. c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
  620. if c2pwrite is None:
  621. _, c2pwrite = _subprocess.CreatePipe(None, 0)
  622. elif stdout == PIPE:
  623. c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
  624. elif isinstance(stdout, int):
  625. c2pwrite = msvcrt.get_osfhandle(stdout)
  626. else:
  627. # Assuming file-like object
  628. c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  629. c2pwrite = self._make_inheritable(c2pwrite)
  630. if stderr is None:
  631. errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
  632. if errwrite is None:
  633. _, errwrite = _subprocess.CreatePipe(None, 0)
  634. elif stderr == PIPE:
  635. errread, errwrite = _subprocess.CreatePipe(None, 0)
  636. elif stderr == STDOUT:
  637. errwrite = c2pwrite.handle # pass id to not close it
  638. elif isinstance(stderr, int):
  639. errwrite = msvcrt.get_osfhandle(stderr)
  640. else:
  641. # Assuming file-like object
  642. errwrite = msvcrt.get_osfhandle(stderr.fileno())
  643. errwrite = self._make_inheritable(errwrite)
  644. return (p2cread, p2cwrite,
  645. c2pread, c2pwrite,
  646. errread, errwrite)
  647. def _make_inheritable(self, handle):
  648. """Return a duplicate of handle, which is inheritable"""
  649. dupl = _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
  650. handle, _subprocess.GetCurrentProcess(), 0, 1,
  651. _subprocess.DUPLICATE_SAME_ACCESS)
  652. # If the initial handle was obtained with CreatePipe, close it.
  653. if not isinstance(handle, int):
  654. handle.Close()
  655. return dupl
  656. def _find_w9xpopen(self):
  657. """Find and return absolut path to w9xpopen.exe"""
  658. w9xpopen = os.path.join(
  659. os.path.dirname(_subprocess.GetModuleFileName(0)),
  660. "w9xpopen.exe")
  661. if not os.path.exists(w9xpopen):
  662. # Eeek - file-not-found - possibly an embedding
  663. # situation - see if we can locate it in sys.exec_prefix
  664. w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
  665. "w9xpopen.exe")
  666. if not os.path.exists(w9xpopen):
  667. raise RuntimeError("Cannot locate w9xpopen.exe, which is "
  668. "needed for Popen to work with your "
  669. "shell or platform.")
  670. return w9xpopen
  671. def _execute_child(self, args, executable, preexec_fn, close_fds,
  672. cwd, env, universal_newlines,
  673. startupinfo, creationflags, shell,
  674. p2cread, p2cwrite,
  675. c2pread, c2pwrite,
  676. errread, errwrite):
  677. """Execute program (MS Windows version)"""
  678. if not isinstance(args, types.StringTypes):
  679. args = list2cmdline(args)
  680. # Process startup details
  681. if startupinfo is None:
  682. startupinfo = STARTUPINFO()
  683. if None not in (p2cread, c2pwrite, errwrite):
  684. startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
  685. startupinfo.hStdInput = p2cread
  686. startupinfo.hStdOutput = c2pwrite
  687. startupinfo.hStdError = errwrite
  688. if shell:
  689. startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
  690. startupinfo.wShowWindow = _subprocess.SW_HIDE
  691. comspec = os.environ.get("COMSPEC", "cmd.exe")
  692. args = '{} /c "{}"'.format (comspec, args)
  693. if (_subprocess.GetVersion() >= 0x80000000 or
  694. os.path.basename(comspec).lower() == "command.com"):
  695. # Win9x, or using command.com on NT. We need to
  696. # use the w9xpopen intermediate program. For more
  697. # information, see KB Q150956
  698. # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
  699. w9xpopen = self._find_w9xpopen()
  700. args = '"%s" %s' % (w9xpopen, args)
  701. # Not passing CREATE_NEW_CONSOLE has been known to
  702. # cause random failures on win9x. Specifically a
  703. # dialog: "Your program accessed mem currently in
  704. # use at xxx" and a hopeful warning about the
  705. # stability of your system. Cost is Ctrl+C wont
  706. # kill children.
  707. creationflags |= _subprocess.CREATE_NEW_CONSOLE
  708. # Start the process
  709. try:
  710. hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
  711. # no special security
  712. None, None,
  713. int(not close_fds),
  714. creationflags,
  715. env,
  716. cwd,
  717. startupinfo)
  718. except pywintypes.error, e:
  719. # Translate pywintypes.error to WindowsError, which is
  720. # a subclass of OSError. FIXME: We should really
  721. # translate errno using _sys_errlist (or similar), but
  722. # how can this be done from Python?
  723. raise WindowsError(*e.args)
  724. finally:
  725. # Child is launched. Close the parent's copy of those pipe
  726. # handles that only the child should have open. You need
  727. # to make sure that no handles to the write end of the
  728. # output pipe are maintained in this process or else the
  729. # pipe will not close when the child process exits and the
  730. # ReadFile will hang.
  731. if p2cread is not None:
  732. p2cread.Close()
  733. if c2pwrite is not None:
  734. c2pwrite.Close()
  735. if errwrite is not None:
  736. errwrite.Close()
  737. # Retain the process handle, but close the thread handle
  738. self._child_created = True
  739. self._handle = hp
  740. self.pid = pid
  741. ht.Close()
  742. def _internal_poll(self, _deadstate=None,
  743. _WaitForSingleObject=_subprocess.WaitForSingleObject,
  744. _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
  745. _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
  746. """Check if child process has terminated. Returns returncode
  747. attribute.
  748. This method is called by __del__, so it can only refer to objects
  749. in its local scope.
  750. """
  751. if self.returncode is None:
  752. if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
  753. self.returncode = _GetExitCodeProcess(self._handle)
  754. return self.returncode
  755. def wait(self):
  756. """Wait for child process to terminate. Returns returncode
  757. attribute."""
  758. if self.returncode is None:
  759. _subprocess.WaitForSingleObject(self._handle,
  760. _subprocess.INFINITE)
  761. self.returncode = _subprocess.GetExitCodeProcess(self._handle)
  762. return self.returncode
  763. def _readerthread(self, fh, buffer):
  764. buffer.append(fh.read())
  765. def _communicate(self, input):
  766. stdout = None # Return
  767. stderr = None # Return
  768. if self.stdout:
  769. stdout = []
  770. stdout_thread = threading.Thread(target=self._readerthread,
  771. args=(self.stdout, stdout))
  772. stdout_thread.setDaemon(True)
  773. stdout_thread.start()
  774. if self.stderr:
  775. stderr = []
  776. stderr_thread = threading.Thread(target=self._readerthread,
  777. args=(self.stderr, stderr))
  778. stderr_thread.setDaemon(True)
  779. stderr_thread.start()
  780. if self.stdin:
  781. if input is not None:
  782. try:
  783. self.stdin.write(input)
  784. except IOError as e:
  785. if e.errno != errno.EPIPE:
  786. raise
  787. self.stdin.close()
  788. if self.stdout:
  789. stdout_thread.join()
  790. if self.stderr:
  791. stderr_thread.join()
  792. # All data exchanged. Translate lists into strings.
  793. if stdout is not None:
  794. stdout = stdout[0]
  795. if stderr is not None:
  796. stderr = stderr[0]
  797. # Translate newlines, if requested. We cannot let the file
  798. # object do the translation: It is based on stdio, which is
  799. # impossible to combine with select (unless forcing no
  800. # buffering).
  801. if self.universal_newlines and hasattr(file, 'newlines'):
  802. if stdout:
  803. stdout = self._translate_newlines(stdout)
  804. if stderr:
  805. stderr = self._translate_newlines(stderr)
  806. self.wait()
  807. return (stdout, stderr)
  808. def send_signal(self, sig):
  809. """Send a signal to the process
  810. """
  811. if sig == signal.SIGTERM:
  812. self.terminate()
  813. elif sig == signal.CTRL_C_EVENT:
  814. os.kill(self.pid, signal.CTRL_C_EVENT)
  815. elif sig == signal.CTRL_BREAK_EVENT:
  816. os.kill(self.pid, signal.CTRL_BREAK_EVENT)
  817. else:
  818. raise ValueError("Unsupported signal: {}".format(sig))
  819. def terminate(self):
  820. """Terminates the process
  821. """
  822. _subprocess.TerminateProcess(self._handle, 1)
  823. kill = terminate
  824. else:
  825. #
  826. # POSIX methods
  827. #
  828. def _get_handles(self, stdin, stdout, stderr):
  829. """Construct and return tuple with IO objects:
  830. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  831. """
  832. p2cread, p2cwrite = None, None
  833. c2pread, c2pwrite = None, None
  834. errread, errwrite = None, None
  835. if stdin is None:
  836. pass
  837. elif stdin == PIPE:
  838. p2cread, p2cwrite = self.pipe_cloexec()
  839. elif isinstance(stdin, int):
  840. p2cread = stdin
  841. else:
  842. # Assuming file-like object
  843. p2cread = stdin.fileno()
  844. if stdout is None:
  845. pass
  846. elif stdout == PIPE:
  847. c2pread, c2pwrite = self.pipe_cloexec()
  848. elif isinstance(stdout, int):
  849. c2pwrite = stdout
  850. else:
  851. # Assuming file-like object
  852. c2pwrite = stdout.fileno()
  853. if stderr is None:
  854. pass
  855. elif stderr == PIPE:
  856. errread, errwrite = self.pipe_cloexec()
  857. elif stderr == STDOUT:
  858. errwrite = c2pwrite
  859. elif isinstance(stderr, int):
  860. errwrite = stderr
  861. else:
  862. # Assuming file-like object
  863. errwrite = stderr.fileno()
  864. return (p2cread, p2cwrite,
  865. c2pread, c2pwrite,
  866. errread, errwrite)
  867. def _set_cloexec_flag(self, fd, cloexec=True):
  868. try:
  869. cloexec_flag = fcntl.FD_CLOEXEC
  870. except AttributeError:
  871. cloexec_flag = 1
  872. old = fcntl.fcntl(fd, fcntl.F_GETFD)
  873. if cloexec:
  874. fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  875. else:
  876. fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
  877. def pipe_cloexec(self):
  878. """Create a pipe with FDs set CLOEXEC."""
  879. # Pipes' FDs are set CLOEXEC by default because we don't want them
  880. # to be inherited by other subprocesses: the CLOEXEC flag is removed
  881. # from the child's FDs by _dup2(), between fork() and exec().
  882. # This is not atomic: we would need the pipe2() syscall for that.
  883. r, w = os.pipe()
  884. self._set_cloexec_flag(r)
  885. self._set_cloexec_flag(w)
  886. return r, w
  887. def _close_fds(self, but):
  888. if hasattr(os, 'closerange'):
  889. os.closerange(3, but)
  890. os.closerange(but + 1, MAXFD)
  891. else:
  892. for i in xrange(3, MAXFD):
  893. if i == but:
  894. continue
  895. try:
  896. os.close(i)
  897. except:
  898. pass
  899. def _execute_child(self, args, executable, preexec_fn, close_fds,
  900. cwd, env, universal_newlines,
  901. startupinfo, creationflags, shell,
  902. p2cread, p2cwrite,
  903. c2pread, c2pwrite,
  904. errread, errwrite):
  905. """Execute program (POSIX version)"""
  906. if isinstance(args, types.StringTypes):
  907. args = [args]
  908. else:
  909. args = list(args)
  910. if shell:
  911. args = ["/bin/sh", "-c"] + args
  912. if executable:
  913. args[0] = executable
  914. if executable is None:
  915. executable = args[0]
  916. # For transferring possible exec failure from child to parent
  917. # The first char specifies the exception type: 0 means
  918. # OSError, 1 means some other error.
  919. errpipe_read, errpipe_write = self.pipe_cloexec()
  920. try:
  921. try:
  922. gc_was_enabled = gc.isenabled()
  923. # Disable gc to avoid bug where gc -> file_dealloc ->
  924. # write to stderr -> hang. http://bugs.python.org/issue1336
  925. gc.disable()
  926. try:
  927. self.pid = os.fork()
  928. except:
  929. if gc_was_enabled:
  930. gc.enable()
  931. raise
  932. self._child_created = True
  933. if self.pid == 0:
  934. # Child
  935. try:
  936. # Close parent's pipe ends
  937. if p2cwrite is not None:
  938. os.close(p2cwrite)
  939. if c2pread is not None:
  940. os.close(c2pread)
  941. if errread is not None:
  942. os.close(errread)
  943. os.close(errpipe_read)
  944. # When duping fds, if there arises a situation
  945. # where one of the fds is either 0, 1 or 2, it
  946. # is possible that it is overwritten (#12607).
  947. if c2pwrite == 0:
  948. c2pwrite = os.dup(c2pwrite)
  949. if errwrite == 0 or errwrite == 1:
  950. errwrite = os.dup(errwrite)
  951. # Dup fds for child
  952. def _dup2(a, b):
  953. # dup2() removes the CLOEXEC flag but
  954. # we must do it ourselves if dup2()
  955. # would be a no-op (issue #10806).
  956. if a == b:
  957. self._set_cloexec_flag(a, False)
  958. elif a is not None:
  959. os.dup2(a, b)
  960. _dup2(p2cread, 0)
  961. _dup2(c2pwrite, 1)
  962. _dup2(errwrite, 2)
  963. # Close pipe fds. Make sure we don't close the
  964. # same fd more than once, or standard fds.
  965. closed = { None }
  966. for fd in [p2cread, c2pwrite, errwrite]:
  967. if fd not in closed and fd > 2:
  968. os.close(fd)
  969. closed.add(fd)
  970. # Close all other fds, if asked for
  971. if close_fds:
  972. self._close_fds(but=errpipe_write)
  973. if cwd is not None:
  974. os.chdir(cwd)
  975. if preexec_fn:
  976. preexec_fn()
  977. if env is None:
  978. os.execvp(executable, args)
  979. else:
  980. os.execvpe(executable, args, env)
  981. except:
  982. exc_type, exc_value, tb = sys.exc_info()
  983. # Save the traceback and attach it to the exception object
  984. exc_lines = traceback.format_exception(exc_type,
  985. exc_value,
  986. tb)
  987. exc_value.child_traceback = ''.join(exc_lines)
  988. os.write(errpipe_write, pickle.dumps(exc_value))
  989. # This exitcode won't be reported to applications, so it
  990. # really doesn't matter what we return.
  991. os._exit(255)
  992. # Parent
  993. if gc_was_enabled:
  994. gc.enable()
  995. finally:
  996. # be sure the FD is closed no matter what
  997. os.close(errpipe_write)
  998. if p2cread is not None and p2cwrite is not None:
  999. os.close(p2cread)
  1000. if c2pwrite is not None and c2pread is not None:
  1001. os.close(c2pwrite)
  1002. if errwrite is not None and errread is not None:
  1003. os.close(errwrite)
  1004. # Wait for exec to fail or succeed; possibly raising exception
  1005. # Exception limited to 1M
  1006. data = _eintr_retry_call(os.read, errpipe_read, 1048576)
  1007. finally:
  1008. # be sure the FD is closed no matter what
  1009. os.close(errpipe_read)
  1010. if data != "":
  1011. try:
  1012. _eintr_retry_call(os.waitpid, self.pid, 0)
  1013. except OSError as e:
  1014. if e.errno != errno.ECHILD:
  1015. raise
  1016. child_exception = pickle.loads(data)
  1017. for fd in (p2cwrite, c2pread, errread):
  1018. if fd is not None:
  1019. os.close(fd)
  1020. raise child_exception
  1021. def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
  1022. _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
  1023. _WEXITSTATUS=os.WEXITSTATUS):
  1024. # This method is called (indirectly) by __del__, so it cannot
  1025. # refer to anything outside of its local scope."""
  1026. if _WIFSIGNALED(sts):
  1027. self.returncode = -_WTERMSIG(sts)
  1028. elif _WIFEXITED(sts):
  1029. self.returncode = _WEXITSTATUS(sts)
  1030. else:
  1031. # Should never happen
  1032. raise RuntimeError("Unknown child exit status!")
  1033. def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
  1034. _WNOHANG=os.WNOHANG, _os_error=os.error):
  1035. """Check if child process has terminated. Returns returncode
  1036. attribute.
  1037. This method is called by __del__, so it cannot reference anything
  1038. outside of the local scope (nor can any methods it calls).
  1039. """
  1040. if self.returncode is None:
  1041. try:
  1042. pid, sts = _waitpid(self.pid, _WNOHANG)
  1043. if pid == self.pid:
  1044. self._handle_exitstatus(sts)
  1045. except _os_error:
  1046. if _deadstate is not None:
  1047. self.returncode = _deadstate
  1048. return self.returncode
  1049. def wait(self):
  1050. """Wait for child process to terminate. Returns returncode
  1051. attribute."""
  1052. if self.returncode is None:
  1053. try:
  1054. pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
  1055. except OSError as e:
  1056. if e.errno != errno.ECHILD:
  1057. raise
  1058. # This happens if SIGCLD is set to be ignored or waiting
  1059. # for child processes has otherwise been disabled for our
  1060. # process. This child is dead, we can't get the status.
  1061. sts = 0
  1062. self._handle_exitstatus(sts)
  1063. return self.returncode
  1064. def _communicate(self, input):
  1065. if self.stdin:
  1066. # Flush stdio buffer. This might block, if the user has
  1067. # been writing to .stdin in an uncontrolled fashion.
  1068. self.stdin.flush()
  1069. if not input:
  1070. self.stdin.close()
  1071. if _has_poll:
  1072. stdout, stderr = self._communicate_with_poll(input)
  1073. else:
  1074. stdout, stderr = self._communicate_with_select(input)
  1075. # All data exchanged. Translate lists into strings.
  1076. if stdout is not None:
  1077. stdout = ''.join(stdout)
  1078. if stderr is not None:
  1079. stderr = ''.join(stderr)
  1080. # Translate newlines, if requested. We cannot let the file
  1081. # object do the translation: It is based on stdio, which is
  1082. # impossible to combine with select (unless forcing no
  1083. # buffering).
  1084. if self.universal_newlines and hasattr(file, 'newlines'):
  1085. if stdout:
  1086. stdout = self._translate_newlines(stdout)
  1087. if stderr:
  1088. stderr = self._translate_newlines(stderr)
  1089. self.wait()
  1090. return (stdout, stderr)
  1091. def _communicate_with_poll(self, input):
  1092. stdout = None # Return
  1093. stderr = None # Return
  1094. fd2file = {}
  1095. fd2output = {}
  1096. poller = select.poll()
  1097. def register_and_append(file_obj, eventmask):
  1098. poller.register(file_obj.fileno(), eventmask)
  1099. fd2file[file_obj.fileno()] = file_obj
  1100. def close_unregister_and_remove(fd):
  1101. poller.unregister(fd)
  1102. fd2file[fd].close()
  1103. fd2file.pop(fd)
  1104. if self.stdin and input:
  1105. register_and_append(self.stdin, select.POLLOUT)
  1106. select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
  1107. if self.stdout:
  1108. register_and_append(self.stdout, select_POLLIN_POLLPRI)
  1109. fd2output[self.stdout.fileno()] = stdout = []
  1110. if self.stderr:
  1111. register_and_append(self.stderr, select_POLLIN_POLLPRI)
  1112. fd2output[self.stderr.fileno()] = stderr = []
  1113. input_offset = 0
  1114. while fd2file:
  1115. try:
  1116. ready = poller.poll()
  1117. except select.error, e:
  1118. if e.args[0] == errno.EINTR:
  1119. continue
  1120. raise
  1121. for fd, mode in ready:
  1122. if mode & select.POLLOUT:
  1123. chunk = input[input_offset : input_offset + _PIPE_BUF]
  1124. try:
  1125. input_offset += os.write(fd, chunk)
  1126. except OSError as e:
  1127. if e.errno == errno.EPIPE:
  1128. close_unregister_and_remove(fd)
  1129. else:
  1130. raise
  1131. else:
  1132. if input_offset >= len(input):
  1133. close_unregister_and_remove(fd)
  1134. elif mode & select_POLLIN_POLLPRI:
  1135. data = os.read(fd, 4096)
  1136. if not data:
  1137. close_unregister_and_remove(fd)
  1138. fd2output[fd].append(data)
  1139. else:
  1140. # Ignore hang up or errors.
  1141. close_unregister_and_remove(fd)
  1142. return (stdout, stderr)
  1143. def _communicate_with_select(self, input):
  1144. read_set = []
  1145. write_set = []
  1146. stdout = None # Return
  1147. stderr = None # Return
  1148. if self.stdin and input:
  1149. write_set.append(self.stdin)
  1150. if self.stdout:
  1151. read_set.append(self.stdout)
  1152. stdout = []
  1153. if self.stderr:
  1154. read_set.append(self.stderr)
  1155. stderr = []
  1156. input_offset = 0
  1157. while read_set or write_set:
  1158. try:
  1159. rlist, wlist, xlist = select.select(read_set, write_set, [])
  1160. except select.error, e:
  1161. if e.args[0] == errno.EINTR:
  1162. continue
  1163. raise
  1164. if self.stdin in wlist:
  1165. chunk = input[input_offset : input_offset + _PIPE_BUF]
  1166. try:
  1167. bytes_written = os.write(self.stdin.fileno(), chunk)
  1168. except OSError as e:
  1169. if e.errno == errno.EPIPE:
  1170. self.stdin.close()
  1171. write_set.remove(self.stdin)
  1172. else:
  1173. raise
  1174. else:
  1175. input_offset += bytes_written
  1176. if input_offset >= len(input):
  1177. self.stdin.close()
  1178. write_set.remove(self.stdin)
  1179. if self.stdout in rlist:
  1180. data = os.read(self.stdout.fileno(), 1024)
  1181. if data == "":
  1182. self.stdout.close()
  1183. read_set.remove(self.stdout)
  1184. stdout.append(data)
  1185. if self.stderr in rlist:
  1186. data = os.read(self.stderr.fileno(), 1024)
  1187. if data == "":
  1188. self.stderr.close()
  1189. read_set.remove(self.stderr)
  1190. stderr.append(data)
  1191. return (stdout, stderr)
  1192. def send_signal(self, sig):
  1193. """Send a signal to the process
  1194. """
  1195. os.kill(self.pid, sig)
  1196. def terminate(self):
  1197. """Terminate the process with SIGTERM
  1198. """
  1199. self.send_signal(signal.SIGTERM)
  1200. def kill(self):
  1201. """Kill the process with SIGKILL
  1202. """
  1203. self.send_signal(signal.SIGKILL)
  1204. def _demo_posix():
  1205. #
  1206. # Example 1: Simple redirection: Get process list
  1207. #
  1208. plist = Popen(["ps"], stdout=PIPE).communicate()[0]
  1209. print "Process list:"
  1210. print plist
  1211. #
  1212. # Example 2: Change uid before executing child
  1213. #
  1214. if os.getuid() == 0:
  1215. p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
  1216. p.wait()
  1217. #
  1218. # Example 3: Connecting several subprocesses
  1219. #
  1220. print "Looking for 'hda'..."
  1221. p1 = Popen(["dmesg"], stdout=PIPE)
  1222. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  1223. print repr(p2.communicate()[0])
  1224. #
  1225. # Example 4: Catch execution error
  1226. #
  1227. print
  1228. print "Trying a weird file..."
  1229. try:
  1230. print Popen(["/this/path/does/not/exist"]).communicate()
  1231. except OSError, e:
  1232. if e.errno == errno.ENOENT:
  1233. print "The file didn't exist. I thought so..."
  1234. print "Child traceback:"
  1235. print e.child_traceback
  1236. else:
  1237. print "Error", e.errno
  1238. else:
  1239. print >>sys.stderr, "Gosh. No error."
  1240. def _demo_windows():
  1241. #
  1242. # Example 1: Connecting several subprocesses
  1243. #
  1244. print "Looking for 'PROMPT' in set output..."
  1245. p1 = Popen("set", stdout=PIPE, shell=True)
  1246. p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
  1247. print repr(p2.communicate()[0])
  1248. #
  1249. # Example 2: Simple execution of program
  1250. #
  1251. print "Executing calc..."
  1252. p = Popen("calc")
  1253. p.wait()
  1254. if __name__ == "__main__":
  1255. if mswindows:
  1256. _demo_windows()
  1257. else:
  1258. _demo_posix()