Advertisement
Guest User

Untitled

a guest
Aug 31st, 2016
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 60.08 KB | None | 0 0
  1. # subprocess - Subprocesses with accessible I/O streams
  2. #
  3. # For more information about this module, see PEP 324.
  4. #
  5. # Copyright (c) 2003-2005 by Peter Astrand <[email protected]>
  6. #
  7. # Licensed to PSF under a Contributor Agreement.
  8. # See http://www.python.org/2.4/license for licensing details.
  9.  
  10. r"""subprocess - Subprocesses with accessible I/O streams
  11.  
  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 older modules and functions:
  15.  
  16. os.system
  17. os.spawn*
  18. os.popen*
  19. popen2.*
  20. commands.*
  21.  
  22. Information about how the subprocess module can be used to replace these
  23. modules and functions can be found below.
  24.  
  25.  
  26.  
  27. Using the subprocess module
  28. ===========================
  29. This module defines one class called Popen:
  30.  
  31. class Popen(args, bufsize=0, executable=None,
  32. stdin=None, stdout=None, stderr=None,
  33. preexec_fn=None, close_fds=False, shell=False,
  34. cwd=None, env=None, universal_newlines=False,
  35. startupinfo=None, creationflags=0):
  36.  
  37.  
  38. Arguments are:
  39.  
  40. args should be a string, or a sequence of program arguments. The
  41. program to execute is normally the first item in the args sequence or
  42. string, but can be explicitly set by using the executable argument.
  43.  
  44. On UNIX, with shell=False (default): In this case, the Popen class
  45. uses os.execvp() to execute the child program. args should normally
  46. be a sequence. A string will be treated as a sequence with the string
  47. as the only item (the program to execute).
  48.  
  49. On UNIX, with shell=True: If args is a string, it specifies the
  50. command string to execute through the shell. If args is a sequence,
  51. the first item specifies the command string, and any additional items
  52. will be treated as additional shell arguments.
  53.  
  54. On Windows: the Popen class uses CreateProcess() to execute the child
  55. program, which operates on strings. If args is a sequence, it will be
  56. converted to a string using the list2cmdline method. Please note that
  57. not all MS Windows applications interpret the command line the same
  58. way: The list2cmdline is designed for applications using the same
  59. rules as the MS C runtime.
  60.  
  61. bufsize, if given, has the same meaning as the corresponding argument
  62. to the built-in open() function: 0 means unbuffered, 1 means line
  63. buffered, any other positive value means use a buffer of
  64. (approximately) that size. A negative bufsize means to use the system
  65. default, which usually means fully buffered. The default value for
  66. bufsize is 0 (unbuffered).
  67.  
  68. stdin, stdout and stderr specify the executed programs' standard
  69. input, standard output and standard error file handles, respectively.
  70. Valid values are PIPE, an existing file descriptor (a positive
  71. integer), an existing file object, and None. PIPE indicates that a
  72. new pipe to the child should be created. With None, no redirection
  73. will occur; the child's file handles will be inherited from the
  74. parent. Additionally, stderr can be STDOUT, which indicates that the
  75. stderr data from the applications should be captured into the same
  76. file handle as for stdout.
  77.  
  78. If preexec_fn is set to a callable object, this object will be called
  79. in the child process just before the child is executed.
  80.  
  81. If close_fds is true, all file descriptors except 0, 1 and 2 will be
  82. closed before the child process is executed.
  83.  
  84. if shell is true, the specified command will be executed through the
  85. shell.
  86.  
  87. If cwd is not None, the current directory will be changed to cwd
  88. before the child is executed.
  89.  
  90. If env is not None, it defines the environment variables for the new
  91. process.
  92.  
  93. If universal_newlines is true, the file objects stdout and stderr are
  94. opened as a text files, but lines may be terminated by any of '\n',
  95. the Unix end-of-line convention, '\r', the Macintosh convention or
  96. '\r\n', the Windows convention. All of these external representations
  97. are seen as '\n' by the Python program. Note: This feature is only
  98. available if Python is built with universal newline support (the
  99. default). Also, the newlines attribute of the file objects stdout,
  100. stdin and stderr are not updated by the communicate() method.
  101.  
  102. The startupinfo and creationflags, if given, will be passed to the
  103. underlying CreateProcess() function. They can specify things such as
  104. appearance of the main window and priority for the new process.
  105. (Windows only)
  106.  
  107.  
  108. This module also defines some shortcut functions:
  109.  
  110. call(*popenargs, **kwargs):
  111. Run command with arguments. Wait for command to complete, then
  112. return the returncode attribute.
  113.  
  114. The arguments are the same as for the Popen constructor. Example:
  115.  
  116. retcode = call(["ls", "-l"])
  117.  
  118. check_call(*popenargs, **kwargs):
  119. Run command with arguments. Wait for command to complete. If the
  120. exit code was zero then return, otherwise raise
  121. CalledProcessError. The CalledProcessError object will have the
  122. return code in the returncode attribute.
  123.  
  124. The arguments are the same as for the Popen constructor. Example:
  125.  
  126. check_call(["ls", "-l"])
  127.  
  128. check_output(*popenargs, **kwargs):
  129. Run command with arguments and return its output as a byte string.
  130.  
  131. If the exit code was non-zero it raises a CalledProcessError. The
  132. CalledProcessError object will have the return code in the returncode
  133. attribute and output in the output attribute.
  134.  
  135. The arguments are the same as for the Popen constructor. Example:
  136.  
  137. output = check_output(["ls", "-l", "/dev/null"])
  138.  
  139.  
  140. Exceptions
  141. ----------
  142. Exceptions raised in the child process, before the new program has
  143. started to execute, will be re-raised in the parent. Additionally,
  144. the exception object will have one extra attribute called
  145. 'child_traceback', which is a string containing traceback information
  146. from the child's point of view.
  147.  
  148. The most common exception raised is OSError. This occurs, for
  149. example, when trying to execute a non-existent file. Applications
  150. should prepare for OSErrors.
  151.  
  152. A ValueError will be raised if Popen is called with invalid arguments.
  153.  
  154. check_call() and check_output() will raise CalledProcessError, if the
  155. called process returns a non-zero return code.
  156.  
  157.  
  158. Security
  159. --------
  160. Unlike some other popen functions, this implementation will never call
  161. /bin/sh implicitly. This means that all characters, including shell
  162. metacharacters, can safely be passed to child processes.
  163.  
  164.  
  165. Popen objects
  166. =============
  167. Instances of the Popen class have the following methods:
  168.  
  169. poll()
  170. Check if child process has terminated. Returns returncode
  171. attribute.
  172.  
  173. wait()
  174. Wait for child process to terminate. Returns returncode attribute.
  175.  
  176. communicate(input=None)
  177. Interact with process: Send data to stdin. Read data from stdout
  178. and stderr, until end-of-file is reached. Wait for process to
  179. terminate. The optional input argument should be a string to be
  180. sent to the child process, or None, if no data should be sent to
  181. the child.
  182.  
  183. communicate() returns a tuple (stdout, stderr).
  184.  
  185. Note: The data read is buffered in memory, so do not use this
  186. method if the data size is large or unlimited.
  187.  
  188. The following attributes are also available:
  189.  
  190. stdin
  191. If the stdin argument is PIPE, this attribute is a file object
  192. that provides input to the child process. Otherwise, it is None.
  193.  
  194. stdout
  195. If the stdout argument is PIPE, this attribute is a file object
  196. that provides output from the child process. Otherwise, it is
  197. None.
  198.  
  199. stderr
  200. If the stderr argument is PIPE, this attribute is file object that
  201. provides error output from the child process. Otherwise, it is
  202. None.
  203.  
  204. pid
  205. The process ID of the child process.
  206.  
  207. returncode
  208. The child return code. A None value indicates that the process
  209. hasn't terminated yet. A negative value -N indicates that the
  210. child was terminated by signal N (UNIX only).
  211.  
  212.  
  213. Replacing older functions with the subprocess module
  214. ====================================================
  215. In this section, "a ==> b" means that b can be used as a replacement
  216. for a.
  217.  
  218. Note: All functions in this section fail (more or less) silently if
  219. the executed program cannot be found; this module raises an OSError
  220. exception.
  221.  
  222. In the following examples, we assume that the subprocess module is
  223. imported with "from subprocess import *".
  224.  
  225.  
  226. Replacing /bin/sh shell backquote
  227. ---------------------------------
  228. output=`mycmd myarg`
  229. ==>
  230. output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
  231.  
  232.  
  233. Replacing shell pipe line
  234. -------------------------
  235. output=`dmesg | grep hda`
  236. ==>
  237. p1 = Popen(["dmesg"], stdout=PIPE)
  238. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  239. output = p2.communicate()[0]
  240.  
  241.  
  242. Replacing os.system()
  243. ---------------------
  244. sts = os.system("mycmd" + " myarg")
  245. ==>
  246. p = Popen("mycmd" + " myarg", shell=True)
  247. pid, sts = os.waitpid(p.pid, 0)
  248.  
  249. Note:
  250.  
  251. * Calling the program through the shell is usually not required.
  252.  
  253. * It's easier to look at the returncode attribute than the
  254. exitstatus.
  255.  
  256. A more real-world example would look like this:
  257.  
  258. try:
  259. retcode = call("mycmd" + " myarg", shell=True)
  260. if retcode < 0:
  261. print >>sys.stderr, "Child was terminated by signal", -retcode
  262. else:
  263. print >>sys.stderr, "Child returned", retcode
  264. except OSError, e:
  265. print >>sys.stderr, "Execution failed:", e
  266.  
  267.  
  268. Replacing os.spawn*
  269. -------------------
  270. P_NOWAIT example:
  271.  
  272. pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
  273. ==>
  274. pid = Popen(["/bin/mycmd", "myarg"]).pid
  275.  
  276.  
  277. P_WAIT example:
  278.  
  279. retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
  280. ==>
  281. retcode = call(["/bin/mycmd", "myarg"])
  282.  
  283.  
  284. Vector example:
  285.  
  286. os.spawnvp(os.P_NOWAIT, path, args)
  287. ==>
  288. Popen([path] + args[1:])
  289.  
  290.  
  291. Environment example:
  292.  
  293. os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
  294. ==>
  295. Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
  296.  
  297.  
  298. Replacing os.popen*
  299. -------------------
  300. pipe = os.popen("cmd", mode='r', bufsize)
  301. ==>
  302. pipe = Popen("cmd", shell=True, bufsize=bufsize, stdout=PIPE).stdout
  303.  
  304. pipe = os.popen("cmd", mode='w', bufsize)
  305. ==>
  306. pipe = Popen("cmd", shell=True, bufsize=bufsize, stdin=PIPE).stdin
  307.  
  308.  
  309. (child_stdin, child_stdout) = os.popen2("cmd", mode, bufsize)
  310. ==>
  311. p = Popen("cmd", shell=True, bufsize=bufsize,
  312. stdin=PIPE, stdout=PIPE, close_fds=True)
  313. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  314.  
  315.  
  316. (child_stdin,
  317. child_stdout,
  318. child_stderr) = os.popen3("cmd", mode, bufsize)
  319. ==>
  320. p = Popen("cmd", shell=True, bufsize=bufsize,
  321. stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
  322. (child_stdin,
  323. child_stdout,
  324. child_stderr) = (p.stdin, p.stdout, p.stderr)
  325.  
  326.  
  327. (child_stdin, child_stdout_and_stderr) = os.popen4("cmd", mode,
  328. bufsize)
  329. ==>
  330. p = Popen("cmd", shell=True, bufsize=bufsize,
  331. stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  332. (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
  333.  
  334. On Unix, os.popen2, os.popen3 and os.popen4 also accept a sequence as
  335. the command to execute, in which case arguments will be passed
  336. directly to the program without shell intervention. This usage can be
  337. replaced as follows:
  338.  
  339. (child_stdin, child_stdout) = os.popen2(["/bin/ls", "-l"], mode,
  340. bufsize)
  341. ==>
  342. p = Popen(["/bin/ls", "-l"], bufsize=bufsize, stdin=PIPE, stdout=PIPE)
  343. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  344.  
  345. Return code handling translates as follows:
  346.  
  347. pipe = os.popen("cmd", 'w')
  348. ...
  349. rc = pipe.close()
  350. if rc is not None and rc % 256:
  351. print "There were some errors"
  352. ==>
  353. process = Popen("cmd", 'w', shell=True, stdin=PIPE)
  354. ...
  355. process.stdin.close()
  356. if process.wait() != 0:
  357. print "There were some errors"
  358.  
  359.  
  360. Replacing popen2.*
  361. ------------------
  362. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
  363. ==>
  364. p = Popen(["somestring"], shell=True, bufsize=bufsize
  365. stdin=PIPE, stdout=PIPE, close_fds=True)
  366. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  367.  
  368. On Unix, popen2 also accepts a sequence as the command to execute, in
  369. which case arguments will be passed directly to the program without
  370. shell intervention. This usage can be replaced as follows:
  371.  
  372. (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize,
  373. mode)
  374. ==>
  375. p = Popen(["mycmd", "myarg"], bufsize=bufsize,
  376. stdin=PIPE, stdout=PIPE, close_fds=True)
  377. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  378.  
  379. The popen2.Popen3 and popen2.Popen4 basically works as subprocess.Popen,
  380. except that:
  381.  
  382. * subprocess.Popen raises an exception if the execution fails
  383. * the capturestderr argument is replaced with the stderr argument.
  384. * stdin=PIPE and stdout=PIPE must be specified.
  385. * popen2 closes all filedescriptors by default, but you have to specify
  386. close_fds=True with subprocess.Popen.
  387. """
  388.  
  389. import sys
  390. mswindows = (sys.platform == "win32")
  391.  
  392. import os
  393. import types
  394. import traceback
  395. import gc
  396. import signal
  397. import errno
  398.  
  399. # Exception classes used by this module.
  400. class CalledProcessError(Exception):
  401. """This exception is raised when a process run by check_call() or
  402. check_output() returns a non-zero exit status.
  403. The exit status will be stored in the returncode attribute;
  404. check_output() will also store the output in the output attribute.
  405. """
  406. def __init__(self, returncode, cmd, output=None):
  407. self.returncode = returncode
  408. self.cmd = cmd
  409. self.output = output
  410. def __str__(self):
  411. return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  412.  
  413.  
  414. if mswindows:
  415. import threading
  416. import msvcrt
  417. import _subprocess
  418. class STARTUPINFO:
  419. dwFlags = 0
  420. hStdInput = None
  421. hStdOutput = None
  422. hStdError = None
  423. wShowWindow = 0
  424. class pywintypes:
  425. error = IOError
  426. else:
  427. import select
  428. _has_poll = hasattr(select, 'poll')
  429. import fcntl
  430. import pickle
  431.  
  432. # When select or poll has indicated that the file is writable,
  433. # we can write up to _PIPE_BUF bytes without risk of blocking.
  434. # POSIX defines PIPE_BUF as >= 512.
  435. _PIPE_BUF = getattr(select, 'PIPE_BUF', 512)
  436.  
  437.  
  438. __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call",
  439. "check_output", "CalledProcessError"]
  440.  
  441. if mswindows:
  442. from _subprocess import (CREATE_NEW_CONSOLE, CREATE_NEW_PROCESS_GROUP,
  443. STD_INPUT_HANDLE, STD_OUTPUT_HANDLE,
  444. STD_ERROR_HANDLE, SW_HIDE,
  445. STARTF_USESTDHANDLES, STARTF_USESHOWWINDOW)
  446.  
  447. __all__.extend(["CREATE_NEW_CONSOLE", "CREATE_NEW_PROCESS_GROUP",
  448. "STD_INPUT_HANDLE", "STD_OUTPUT_HANDLE",
  449. "STD_ERROR_HANDLE", "SW_HIDE",
  450. "STARTF_USESTDHANDLES", "STARTF_USESHOWWINDOW"])
  451. try:
  452. MAXFD = os.sysconf("SC_OPEN_MAX")
  453. except:
  454. MAXFD = 256
  455.  
  456. _active = []
  457.  
  458. def _cleanup():
  459. for inst in _active[:]:
  460. res = inst._internal_poll(_deadstate=sys.maxint)
  461. if res is not None:
  462. try:
  463. _active.remove(inst)
  464. except ValueError:
  465. # This can happen if two threads create a new Popen instance.
  466. # It's harmless that it was already removed, so ignore.
  467. pass
  468.  
  469. PIPE = -1
  470. STDOUT = -2
  471.  
  472.  
  473. def _eintr_retry_call(func, *args):
  474. while True:
  475. try:
  476. return func(*args)
  477. except (OSError, IOError) as e:
  478. if e.errno == errno.EINTR:
  479. continue
  480. raise
  481.  
  482.  
  483. # XXX This function is only used by multiprocessing and the test suite,
  484. # but it's here so that it can be imported when Python is compiled without
  485. # threads.
  486.  
  487. def _args_from_interpreter_flags():
  488. """Return a list of command-line arguments reproducing the current
  489. settings in sys.flags and sys.warnoptions."""
  490. flag_opt_map = {
  491. 'debug': 'd',
  492. # 'inspect': 'i',
  493. # 'interactive': 'i',
  494. 'optimize': 'O',
  495. 'dont_write_bytecode': 'B',
  496. 'no_user_site': 's',
  497. 'no_site': 'S',
  498. 'ignore_environment': 'E',
  499. 'verbose': 'v',
  500. 'bytes_warning': 'b',
  501. 'py3k_warning': '3',
  502. }
  503. args = []
  504. for flag, opt in flag_opt_map.items():
  505. v = getattr(sys.flags, flag)
  506. if v > 0:
  507. args.append('-' + opt * v)
  508. if getattr(sys.flags, 'hash_randomization') != 0:
  509. args.append('-R')
  510. for opt in sys.warnoptions:
  511. args.append('-W' + opt)
  512. return args
  513.  
  514.  
  515. def call(*popenargs, **kwargs):
  516. """Run command with arguments. Wait for command to complete, then
  517. return the returncode attribute.
  518.  
  519. The arguments are the same as for the Popen constructor. Example:
  520.  
  521. retcode = call(["ls", "-l"])
  522. """
  523. return Popen(*popenargs, **kwargs).wait()
  524.  
  525.  
  526. def check_call(*popenargs, **kwargs):
  527. """Run command with arguments. Wait for command to complete. If
  528. the exit code was zero then return, otherwise raise
  529. CalledProcessError. The CalledProcessError object will have the
  530. return code in the returncode attribute.
  531.  
  532. The arguments are the same as for the Popen constructor. Example:
  533.  
  534. check_call(["ls", "-l"])
  535. """
  536. retcode = call(*popenargs, **kwargs)
  537. if retcode:
  538. cmd = kwargs.get("args")
  539. if cmd is None:
  540. cmd = popenargs[0]
  541. raise CalledProcessError(retcode, cmd)
  542. return 0
  543.  
  544.  
  545. def check_output(*popenargs, **kwargs):
  546. r"""Run command with arguments and return its output as a byte string.
  547.  
  548. If the exit code was non-zero it raises a CalledProcessError. The
  549. CalledProcessError object will have the return code in the returncode
  550. attribute and output in the output attribute.
  551.  
  552. The arguments are the same as for the Popen constructor. Example:
  553.  
  554. >>> check_output(["ls", "-l", "/dev/null"])
  555. 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
  556.  
  557. The stdout argument is not allowed as it is used internally.
  558. To capture standard error in the result, use stderr=STDOUT.
  559.  
  560. >>> check_output(["/bin/sh", "-c",
  561. ... "ls -l non_existent_file ; exit 0"],
  562. ... stderr=STDOUT)
  563. 'ls: non_existent_file: No such file or directory\n'
  564. """
  565. if 'stdout' in kwargs:
  566. raise ValueError('stdout argument not allowed, it will be overridden.')
  567. process = Popen(stdout=PIPE, *popenargs, **kwargs)
  568. output, unused_err = process.communicate()
  569. retcode = process.poll()
  570. if retcode:
  571. cmd = kwargs.get("args")
  572. if cmd is None:
  573. cmd = popenargs[0]
  574. raise CalledProcessError(retcode, cmd, output=output)
  575. return output
  576.  
  577.  
  578. def list2cmdline(seq):
  579. """
  580. Translate a sequence of arguments into a command line
  581. string, using the same rules as the MS C runtime:
  582.  
  583. 1) Arguments are delimited by white space, which is either a
  584. space or a tab.
  585.  
  586. 2) A string surrounded by double quotation marks is
  587. interpreted as a single argument, regardless of white space
  588. contained within. A quoted string can be embedded in an
  589. argument.
  590.  
  591. 3) A double quotation mark preceded by a backslash is
  592. interpreted as a literal double quotation mark.
  593.  
  594. 4) Backslashes are interpreted literally, unless they
  595. immediately precede a double quotation mark.
  596.  
  597. 5) If backslashes immediately precede a double quotation mark,
  598. every pair of backslashes is interpreted as a literal
  599. backslash. If the number of backslashes is odd, the last
  600. backslash escapes the next double quotation mark as
  601. described in rule 3.
  602. """
  603.  
  604. # See
  605. # http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
  606. # or search http://msdn.microsoft.com for
  607. # "Parsing C++ Command-Line Arguments"
  608. result = []
  609. needquote = False
  610. for arg in seq:
  611. bs_buf = []
  612.  
  613. # Add a space to separate this argument from the others
  614. if result:
  615. result.append(' ')
  616.  
  617. needquote = (" " in arg) or ("\t" in arg) or not arg
  618. if needquote:
  619. result.append('"')
  620.  
  621. for c in arg:
  622. if c == '\\':
  623. # Don't know if we need to double yet.
  624. bs_buf.append(c)
  625. elif c == '"':
  626. # Double backslashes.
  627. result.append('\\' * len(bs_buf)*2)
  628. bs_buf = []
  629. result.append('\\"')
  630. else:
  631. # Normal char
  632. if bs_buf:
  633. result.extend(bs_buf)
  634. bs_buf = []
  635. result.append(c)
  636.  
  637. # Add remaining backslashes, if any.
  638. if bs_buf:
  639. result.extend(bs_buf)
  640.  
  641. if needquote:
  642. result.extend(bs_buf)
  643. result.append('"')
  644.  
  645. return ''.join(result)
  646.  
  647.  
  648. class Popen(object):
  649. _child_created = False # Set here since __del__ checks it
  650.  
  651. def __init__(self, args, bufsize=0, executable=None,
  652. stdin=None, stdout=None, stderr=None,
  653. preexec_fn=None, close_fds=False, shell=False,
  654. cwd=None, env=None, universal_newlines=False,
  655. startupinfo=None, creationflags=0):
  656. """Create new Popen instance."""
  657. _cleanup()
  658.  
  659. if not isinstance(bufsize, (int, long)):
  660. raise TypeError("bufsize must be an integer")
  661.  
  662. if mswindows:
  663. if preexec_fn is not None:
  664. raise ValueError("preexec_fn is not supported on Windows "
  665. "platforms")
  666. if close_fds and (stdin is not None or stdout is not None or
  667. stderr is not None):
  668. raise ValueError("close_fds is not supported on Windows "
  669. "platforms if you redirect stdin/stdout/stderr")
  670. else:
  671. # POSIX
  672. if startupinfo is not None:
  673. raise ValueError("startupinfo is only supported on Windows "
  674. "platforms")
  675. if creationflags != 0:
  676. raise ValueError("creationflags is only supported on Windows "
  677. "platforms")
  678.  
  679. self.stdin = None
  680. self.stdout = None
  681. self.stderr = None
  682. self.pid = None
  683. self.returncode = None
  684. self.universal_newlines = universal_newlines
  685.  
  686. # Input and output objects. The general principle is like
  687. # this:
  688. #
  689. # Parent Child
  690. # ------ -----
  691. # p2cwrite ---stdin---> p2cread
  692. # c2pread <--stdout--- c2pwrite
  693. # errread <--stderr--- errwrite
  694. #
  695. # On POSIX, the child objects are file descriptors. On
  696. # Windows, these are Windows file handles. The parent objects
  697. # are file descriptors on both platforms. The parent objects
  698. # are None when not using PIPEs. The child objects are None
  699. # when not redirecting.
  700.  
  701. (p2cread, p2cwrite,
  702. c2pread, c2pwrite,
  703. errread, errwrite), to_close = self._get_handles(stdin, stdout, stderr)
  704.  
  705. try:
  706. self._execute_child(args, executable, preexec_fn, close_fds,
  707. cwd, env, universal_newlines,
  708. startupinfo, creationflags, shell, to_close,
  709. p2cread, p2cwrite,
  710. c2pread, c2pwrite,
  711. errread, errwrite)
  712. except Exception:
  713. # Preserve original exception in case os.close raises.
  714. exc_type, exc_value, exc_trace = sys.exc_info()
  715.  
  716. for fd in to_close:
  717. try:
  718. if mswindows:
  719. fd.Close()
  720. else:
  721. os.close(fd)
  722. except EnvironmentError:
  723. pass
  724.  
  725. raise exc_type, exc_value, exc_trace
  726.  
  727. if mswindows:
  728. if p2cwrite is not None:
  729. p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
  730. if c2pread is not None:
  731. c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
  732. if errread is not None:
  733. errread = msvcrt.open_osfhandle(errread.Detach(), 0)
  734.  
  735. if p2cwrite is not None:
  736. self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
  737. if c2pread is not None:
  738. if universal_newlines:
  739. self.stdout = os.fdopen(c2pread, 'rU', bufsize)
  740. else:
  741. self.stdout = os.fdopen(c2pread, 'rb', bufsize)
  742. if errread is not None:
  743. if universal_newlines:
  744. self.stderr = os.fdopen(errread, 'rU', bufsize)
  745. else:
  746. self.stderr = os.fdopen(errread, 'rb', bufsize)
  747.  
  748.  
  749. def _translate_newlines(self, data):
  750. data = data.replace("\r\n", "\n")
  751. data = data.replace("\r", "\n")
  752. return data
  753.  
  754.  
  755. def __del__(self, _maxint=sys.maxint):
  756. # If __init__ hasn't had a chance to execute (e.g. if it
  757. # was passed an undeclared keyword argument), we don't
  758. # have a _child_created attribute at all.
  759. if not self._child_created:
  760. # We didn't get to successfully create a child process.
  761. return
  762. # In case the child hasn't been waited on, check if it's done.
  763. self._internal_poll(_deadstate=_maxint)
  764. if self.returncode is None and _active is not None:
  765. # Child is still running, keep us alive until we can wait on it.
  766. _active.append(self)
  767.  
  768.  
  769. def communicate(self, input=None):
  770. """Interact with process: Send data to stdin. Read data from
  771. stdout and stderr, until end-of-file is reached. Wait for
  772. process to terminate. The optional input argument should be a
  773. string to be sent to the child process, or None, if no data
  774. should be sent to the child.
  775.  
  776. communicate() returns a tuple (stdout, stderr)."""
  777.  
  778. # Optimization: If we are only using one pipe, or no pipe at
  779. # all, using select() or threads is unnecessary.
  780. if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
  781. stdout = None
  782. stderr = None
  783. if self.stdin:
  784. if input:
  785. try:
  786. self.stdin.write(input)
  787. except IOError as e:
  788. if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
  789. raise
  790. self.stdin.close()
  791. elif self.stdout:
  792. stdout = _eintr_retry_call(self.stdout.read)
  793. self.stdout.close()
  794. elif self.stderr:
  795. stderr = _eintr_retry_call(self.stderr.read)
  796. self.stderr.close()
  797. self.wait()
  798. return (stdout, stderr)
  799.  
  800. return self._communicate(input)
  801.  
  802.  
  803. def poll(self):
  804. return self._internal_poll()
  805.  
  806.  
  807. if mswindows:
  808. #
  809. # Windows methods
  810. #
  811. def _get_handles(self, stdin, stdout, stderr):
  812. """Construct and return tuple with IO objects:
  813. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  814. """
  815. to_close = set()
  816. if stdin is None and stdout is None and stderr is None:
  817. return (None, None, None, None, None, None), to_close
  818.  
  819. p2cread, p2cwrite = None, None
  820. c2pread, c2pwrite = None, None
  821. errread, errwrite = None, None
  822.  
  823. if stdin is None:
  824. p2cread = _subprocess.GetStdHandle(_subprocess.STD_INPUT_HANDLE)
  825. if p2cread is None:
  826. p2cread, _ = _subprocess.CreatePipe(None, 0)
  827. elif stdin == PIPE:
  828. p2cread, p2cwrite = _subprocess.CreatePipe(None, 0)
  829. elif isinstance(stdin, int):
  830. p2cread = msvcrt.get_osfhandle(stdin)
  831. else:
  832. # Assuming file-like object
  833. p2cread = msvcrt.get_osfhandle(stdin.fileno())
  834. p2cread = self._make_inheritable(p2cread)
  835. # We just duplicated the handle, it has to be closed at the end
  836. to_close.add(p2cread)
  837. if stdin == PIPE:
  838. to_close.add(p2cwrite)
  839.  
  840. if stdout is None:
  841. c2pwrite = _subprocess.GetStdHandle(_subprocess.STD_OUTPUT_HANDLE)
  842. if c2pwrite is None:
  843. _, c2pwrite = _subprocess.CreatePipe(None, 0)
  844. elif stdout == PIPE:
  845. c2pread, c2pwrite = _subprocess.CreatePipe(None, 0)
  846. elif isinstance(stdout, int):
  847. c2pwrite = msvcrt.get_osfhandle(stdout)
  848. else:
  849. # Assuming file-like object
  850. c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  851. c2pwrite = self._make_inheritable(c2pwrite)
  852. # We just duplicated the handle, it has to be closed at the end
  853. to_close.add(c2pwrite)
  854. if stdout == PIPE:
  855. to_close.add(c2pread)
  856.  
  857. if stderr is None:
  858. errwrite = _subprocess.GetStdHandle(_subprocess.STD_ERROR_HANDLE)
  859. if errwrite is None:
  860. _, errwrite = _subprocess.CreatePipe(None, 0)
  861. elif stderr == PIPE:
  862. errread, errwrite = _subprocess.CreatePipe(None, 0)
  863. elif stderr == STDOUT:
  864. errwrite = c2pwrite
  865. elif isinstance(stderr, int):
  866. errwrite = msvcrt.get_osfhandle(stderr)
  867. else:
  868. # Assuming file-like object
  869. errwrite = msvcrt.get_osfhandle(stderr.fileno())
  870. errwrite = self._make_inheritable(errwrite)
  871. # We just duplicated the handle, it has to be closed at the end
  872. to_close.add(errwrite)
  873. if stderr == PIPE:
  874. to_close.add(errread)
  875.  
  876. return (p2cread, p2cwrite,
  877. c2pread, c2pwrite,
  878. errread, errwrite), to_close
  879.  
  880.  
  881. def _make_inheritable(self, handle):
  882. """Return a duplicate of handle, which is inheritable"""
  883. return _subprocess.DuplicateHandle(_subprocess.GetCurrentProcess(),
  884. handle, _subprocess.GetCurrentProcess(), 0, 1,
  885. _subprocess.DUPLICATE_SAME_ACCESS)
  886.  
  887.  
  888. def _find_w9xpopen(self):
  889. """Find and return absolut path to w9xpopen.exe"""
  890. w9xpopen = os.path.join(
  891. os.path.dirname(_subprocess.GetModuleFileName(0)),
  892. "w9xpopen.exe")
  893. if not os.path.exists(w9xpopen):
  894. # Eeek - file-not-found - possibly an embedding
  895. # situation - see if we can locate it in sys.exec_prefix
  896. w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
  897. "w9xpopen.exe")
  898. if not os.path.exists(w9xpopen):
  899. raise RuntimeError("Cannot locate w9xpopen.exe, which is "
  900. "needed for Popen to work with your "
  901. "shell or platform.")
  902. return w9xpopen
  903.  
  904.  
  905. def _execute_child(self, args, executable, preexec_fn, close_fds,
  906. cwd, env, universal_newlines,
  907. startupinfo, creationflags, shell, to_close,
  908. p2cread, p2cwrite,
  909. c2pread, c2pwrite,
  910. errread, errwrite):
  911. """Execute program (MS Windows version)"""
  912.  
  913. if not isinstance(args, types.StringTypes):
  914. args = list2cmdline(args)
  915.  
  916. # Process startup details
  917. if startupinfo is None:
  918. startupinfo = STARTUPINFO()
  919. if None not in (p2cread, c2pwrite, errwrite):
  920. startupinfo.dwFlags |= _subprocess.STARTF_USESTDHANDLES
  921. startupinfo.hStdInput = p2cread
  922. startupinfo.hStdOutput = c2pwrite
  923. startupinfo.hStdError = errwrite
  924.  
  925. if shell:
  926. startupinfo.dwFlags |= _subprocess.STARTF_USESHOWWINDOW
  927. startupinfo.wShowWindow = _subprocess.SW_HIDE
  928. comspec = os.environ.get("COMSPEC", "cmd.exe")
  929. args = '{} /c "{}"'.format (comspec, args)
  930. if (_subprocess.GetVersion() >= 0x80000000 or
  931. os.path.basename(comspec).lower() == "command.com"):
  932. # Win9x, or using command.com on NT. We need to
  933. # use the w9xpopen intermediate program. For more
  934. # information, see KB Q150956
  935. # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
  936. w9xpopen = self._find_w9xpopen()
  937. args = '"%s" %s' % (w9xpopen, args)
  938. # Not passing CREATE_NEW_CONSOLE has been known to
  939. # cause random failures on win9x. Specifically a
  940. # dialog: "Your program accessed mem currently in
  941. # use at xxx" and a hopeful warning about the
  942. # stability of your system. Cost is Ctrl+C wont
  943. # kill children.
  944. creationflags |= _subprocess.CREATE_NEW_CONSOLE
  945.  
  946. def _close_in_parent(fd):
  947. fd.Close()
  948. to_close.remove(fd)
  949.  
  950. # Start the process
  951. try:
  952. hp, ht, pid, tid = _subprocess.CreateProcess(executable, args,
  953. # no special security
  954. None, None,
  955. int(not close_fds),
  956. creationflags,
  957. env,
  958. cwd,
  959. startupinfo)
  960. except pywintypes.error, e:
  961. # Translate pywintypes.error to WindowsError, which is
  962. # a subclass of OSError. FIXME: We should really
  963. # translate errno using _sys_errlist (or similar), but
  964. # how can this be done from Python?
  965. raise WindowsError(*e.args)
  966. finally:
  967. # Child is launched. Close the parent's copy of those pipe
  968. # handles that only the child should have open. You need
  969. # to make sure that no handles to the write end of the
  970. # output pipe are maintained in this process or else the
  971. # pipe will not close when the child process exits and the
  972. # ReadFile will hang.
  973. if p2cread is not None:
  974. _close_in_parent(p2cread)
  975. if c2pwrite is not None:
  976. _close_in_parent(c2pwrite)
  977. if errwrite is not None:
  978. _close_in_parent(errwrite)
  979.  
  980. # Retain the process handle, but close the thread handle
  981. self._child_created = True
  982. self._handle = hp
  983. self.pid = pid
  984. ht.Close()
  985.  
  986. def _internal_poll(self, _deadstate=None,
  987. _WaitForSingleObject=_subprocess.WaitForSingleObject,
  988. _WAIT_OBJECT_0=_subprocess.WAIT_OBJECT_0,
  989. _GetExitCodeProcess=_subprocess.GetExitCodeProcess):
  990. """Check if child process has terminated. Returns returncode
  991. attribute.
  992.  
  993. This method is called by __del__, so it can only refer to objects
  994. in its local scope.
  995.  
  996. """
  997. if self.returncode is None:
  998. if _WaitForSingleObject(self._handle, 0) == _WAIT_OBJECT_0:
  999. self.returncode = _GetExitCodeProcess(self._handle)
  1000. return self.returncode
  1001.  
  1002.  
  1003. def wait(self):
  1004. """Wait for child process to terminate. Returns returncode
  1005. attribute."""
  1006. if self.returncode is None:
  1007. _subprocess.WaitForSingleObject(self._handle,
  1008. _subprocess.INFINITE)
  1009. self.returncode = _subprocess.GetExitCodeProcess(self._handle)
  1010. return self.returncode
  1011.  
  1012.  
  1013. def _readerthread(self, fh, buffer):
  1014. buffer.append(fh.read())
  1015.  
  1016.  
  1017. def _communicate(self, input):
  1018. stdout = None # Return
  1019. stderr = None # Return
  1020.  
  1021. if self.stdout:
  1022. stdout = []
  1023. stdout_thread = threading.Thread(target=self._readerthread,
  1024. args=(self.stdout, stdout))
  1025. stdout_thread.setDaemon(True)
  1026. stdout_thread.start()
  1027. if self.stderr:
  1028. stderr = []
  1029. stderr_thread = threading.Thread(target=self._readerthread,
  1030. args=(self.stderr, stderr))
  1031. stderr_thread.setDaemon(True)
  1032. stderr_thread.start()
  1033.  
  1034. if self.stdin:
  1035. if input is not None:
  1036. try:
  1037. self.stdin.write(input)
  1038. except IOError as e:
  1039. if e.errno == errno.EPIPE:
  1040. # communicate() should ignore broken pipe error
  1041. pass
  1042. elif (e.errno == errno.EINVAL
  1043. and self.poll() is not None):
  1044. # Issue #19612: stdin.write() fails with EINVAL
  1045. # if the process already exited before the write
  1046. pass
  1047. else:
  1048. raise
  1049. self.stdin.close()
  1050.  
  1051. if self.stdout:
  1052. stdout_thread.join()
  1053. if self.stderr:
  1054. stderr_thread.join()
  1055.  
  1056. # All data exchanged. Translate lists into strings.
  1057. if stdout is not None:
  1058. stdout = stdout[0]
  1059. if stderr is not None:
  1060. stderr = stderr[0]
  1061.  
  1062. # Translate newlines, if requested. We cannot let the file
  1063. # object do the translation: It is based on stdio, which is
  1064. # impossible to combine with select (unless forcing no
  1065. # buffering).
  1066. if self.universal_newlines and hasattr(file, 'newlines'):
  1067. if stdout:
  1068. stdout = self._translate_newlines(stdout)
  1069. if stderr:
  1070. stderr = self._translate_newlines(stderr)
  1071.  
  1072. self.wait()
  1073. return (stdout, stderr)
  1074.  
  1075. def send_signal(self, sig):
  1076. """Send a signal to the process
  1077. """
  1078. if sig == signal.SIGTERM:
  1079. self.terminate()
  1080. elif sig == signal.CTRL_C_EVENT:
  1081. os.kill(self.pid, signal.CTRL_C_EVENT)
  1082. elif sig == signal.CTRL_BREAK_EVENT:
  1083. os.kill(self.pid, signal.CTRL_BREAK_EVENT)
  1084. else:
  1085. raise ValueError("Unsupported signal: {}".format(sig))
  1086.  
  1087. def terminate(self):
  1088. """Terminates the process
  1089. """
  1090. try:
  1091. _subprocess.TerminateProcess(self._handle, 1)
  1092. except OSError as e:
  1093. # ERROR_ACCESS_DENIED (winerror 5) is received when the
  1094. # process already died.
  1095. if e.winerror != 5:
  1096. raise
  1097. rc = _subprocess.GetExitCodeProcess(self._handle)
  1098. if rc == _subprocess.STILL_ACTIVE:
  1099. raise
  1100. self.returncode = rc
  1101.  
  1102. kill = terminate
  1103.  
  1104. else:
  1105. #
  1106. # POSIX methods
  1107. #
  1108. def _get_handles(self, stdin, stdout, stderr):
  1109. """Construct and return tuple with IO objects:
  1110. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  1111. """
  1112. to_close = set()
  1113. p2cread, p2cwrite = None, None
  1114. c2pread, c2pwrite = None, None
  1115. errread, errwrite = None, None
  1116.  
  1117. if stdin is None:
  1118. pass
  1119. elif stdin == PIPE:
  1120. p2cread, p2cwrite = self.pipe_cloexec()
  1121. to_close.update((p2cread, p2cwrite))
  1122. elif isinstance(stdin, int):
  1123. p2cread = stdin
  1124. else:
  1125. # Assuming file-like object
  1126. p2cread = stdin.fileno()
  1127.  
  1128. if stdout is None:
  1129. pass
  1130. elif stdout == PIPE:
  1131. c2pread, c2pwrite = self.pipe_cloexec()
  1132. to_close.update((c2pread, c2pwrite))
  1133. elif isinstance(stdout, int):
  1134. c2pwrite = stdout
  1135. else:
  1136. # Assuming file-like object
  1137. c2pwrite = stdout.fileno()
  1138.  
  1139. if stderr is None:
  1140. pass
  1141. elif stderr == PIPE:
  1142. errread, errwrite = self.pipe_cloexec()
  1143. to_close.update((errread, errwrite))
  1144. elif stderr == STDOUT:
  1145. if c2pwrite is not None:
  1146. errwrite = c2pwrite
  1147. else: # child's stdout is not set, use parent's stdout
  1148. errwrite = sys.__stdout__.fileno()
  1149. elif isinstance(stderr, int):
  1150. errwrite = stderr
  1151. else:
  1152. # Assuming file-like object
  1153. errwrite = stderr.fileno()
  1154.  
  1155. return (p2cread, p2cwrite,
  1156. c2pread, c2pwrite,
  1157. errread, errwrite), to_close
  1158.  
  1159.  
  1160. def _set_cloexec_flag(self, fd, cloexec=True):
  1161. try:
  1162. cloexec_flag = fcntl.FD_CLOEXEC
  1163. except AttributeError:
  1164. cloexec_flag = 1
  1165.  
  1166. old = fcntl.fcntl(fd, fcntl.F_GETFD)
  1167. if cloexec:
  1168. fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  1169. else:
  1170. fcntl.fcntl(fd, fcntl.F_SETFD, old & ~cloexec_flag)
  1171.  
  1172.  
  1173. def pipe_cloexec(self):
  1174. """Create a pipe with FDs set CLOEXEC."""
  1175. # Pipes' FDs are set CLOEXEC by default because we don't want them
  1176. # to be inherited by other subprocesses: the CLOEXEC flag is removed
  1177. # from the child's FDs by _dup2(), between fork() and exec().
  1178. # This is not atomic: we would need the pipe2() syscall for that.
  1179. r, w = os.pipe()
  1180. self._set_cloexec_flag(r)
  1181. self._set_cloexec_flag(w)
  1182. return r, w
  1183.  
  1184.  
  1185. def _close_fds(self, but):
  1186. if hasattr(os, 'closerange'):
  1187. os.closerange(3, but)
  1188. os.closerange(but + 1, MAXFD)
  1189. else:
  1190. for i in xrange(3, MAXFD):
  1191. if i == but:
  1192. continue
  1193. try:
  1194. os.close(i)
  1195. except:
  1196. pass
  1197.  
  1198.  
  1199. def _execute_child(self, args, executable, preexec_fn, close_fds,
  1200. cwd, env, universal_newlines,
  1201. startupinfo, creationflags, shell, to_close,
  1202. p2cread, p2cwrite,
  1203. c2pread, c2pwrite,
  1204. errread, errwrite):
  1205. """Execute program (POSIX version)"""
  1206.  
  1207. if isinstance(args, types.StringTypes):
  1208. args = [args]
  1209. else:
  1210. args = list(args)
  1211.  
  1212. if shell:
  1213. args = ["/bin/sh", "-c"] + args
  1214. if executable:
  1215. args[0] = executable
  1216.  
  1217. if executable is None:
  1218. executable = args[0]
  1219.  
  1220. def _close_in_parent(fd):
  1221. os.close(fd)
  1222. to_close.remove(fd)
  1223.  
  1224. # For transferring possible exec failure from child to parent
  1225. # The first char specifies the exception type: 0 means
  1226. # OSError, 1 means some other error.
  1227. errpipe_read, errpipe_write = self.pipe_cloexec()
  1228. try:
  1229. try:
  1230. gc_was_enabled = gc.isenabled()
  1231. # Disable gc to avoid bug where gc -> file_dealloc ->
  1232. # write to stderr -> hang. http://bugs.python.org/issue1336
  1233. gc.disable()
  1234. try:
  1235. self.pid = os.fork()
  1236. except:
  1237. if gc_was_enabled:
  1238. gc.enable()
  1239. raise
  1240. self._child_created = True
  1241. if self.pid == 0:
  1242. # Child
  1243. try:
  1244. # Close parent's pipe ends
  1245. if p2cwrite is not None:
  1246. os.close(p2cwrite)
  1247. if c2pread is not None:
  1248. os.close(c2pread)
  1249. if errread is not None:
  1250. os.close(errread)
  1251. os.close(errpipe_read)
  1252.  
  1253. # When duping fds, if there arises a situation
  1254. # where one of the fds is either 0, 1 or 2, it
  1255. # is possible that it is overwritten (#12607).
  1256. if c2pwrite == 0:
  1257. c2pwrite = os.dup(c2pwrite)
  1258. if errwrite == 0 or errwrite == 1:
  1259. errwrite = os.dup(errwrite)
  1260.  
  1261. # Dup fds for child
  1262. def _dup2(a, b):
  1263. # dup2() removes the CLOEXEC flag but
  1264. # we must do it ourselves if dup2()
  1265. # would be a no-op (issue #10806).
  1266. if a == b:
  1267. self._set_cloexec_flag(a, False)
  1268. elif a is not None:
  1269. os.dup2(a, b)
  1270. _dup2(p2cread, 0)
  1271. _dup2(c2pwrite, 1)
  1272. _dup2(errwrite, 2)
  1273.  
  1274. # Close pipe fds. Make sure we don't close the
  1275. # same fd more than once, or standard fds.
  1276. closed = { None }
  1277. for fd in [p2cread, c2pwrite, errwrite]:
  1278. if fd not in closed and fd > 2:
  1279. os.close(fd)
  1280. closed.add(fd)
  1281.  
  1282. if cwd is not None:
  1283. os.chdir(cwd)
  1284.  
  1285. if preexec_fn:
  1286. preexec_fn()
  1287.  
  1288. # Close all other fds, if asked for - after
  1289. # preexec_fn(), which may open FDs.
  1290. if close_fds:
  1291. self._close_fds(but=errpipe_write)
  1292.  
  1293. if env is None:
  1294. os.execvp(executable, args)
  1295. else:
  1296. os.execvpe(executable, args, env)
  1297.  
  1298. except:
  1299. exc_type, exc_value, tb = sys.exc_info()
  1300. # Save the traceback and attach it to the exception object
  1301. exc_lines = traceback.format_exception(exc_type,
  1302. exc_value,
  1303. tb)
  1304. exc_value.child_traceback = ''.join(exc_lines)
  1305. os.write(errpipe_write, pickle.dumps(exc_value))
  1306.  
  1307. # This exitcode won't be reported to applications, so it
  1308. # really doesn't matter what we return.
  1309. os._exit(255)
  1310.  
  1311. # Parent
  1312. if gc_was_enabled:
  1313. gc.enable()
  1314. finally:
  1315. # be sure the FD is closed no matter what
  1316. os.close(errpipe_write)
  1317.  
  1318. # Wait for exec to fail or succeed; possibly raising exception
  1319. data = _eintr_retry_call(os.read, errpipe_read, 1048576)
  1320. pickle_bits = []
  1321. while data:
  1322. pickle_bits.append(data)
  1323. data = _eintr_retry_call(os.read, errpipe_read, 1048576)
  1324. data = "".join(pickle_bits)
  1325. finally:
  1326. if p2cread is not None and p2cwrite is not None:
  1327. _close_in_parent(p2cread)
  1328. if c2pwrite is not None and c2pread is not None:
  1329. _close_in_parent(c2pwrite)
  1330. if errwrite is not None and errread is not None:
  1331. _close_in_parent(errwrite)
  1332.  
  1333. # be sure the FD is closed no matter what
  1334. os.close(errpipe_read)
  1335.  
  1336. if data != "":
  1337. try:
  1338. _eintr_retry_call(os.waitpid, self.pid, 0)
  1339. except OSError as e:
  1340. if e.errno != errno.ECHILD:
  1341. raise
  1342. child_exception = pickle.loads(data)
  1343. raise child_exception
  1344.  
  1345.  
  1346. def _handle_exitstatus(self, sts, _WIFSIGNALED=os.WIFSIGNALED,
  1347. _WTERMSIG=os.WTERMSIG, _WIFEXITED=os.WIFEXITED,
  1348. _WEXITSTATUS=os.WEXITSTATUS):
  1349. # This method is called (indirectly) by __del__, so it cannot
  1350. # refer to anything outside of its local scope.
  1351. if _WIFSIGNALED(sts):
  1352. self.returncode = -_WTERMSIG(sts)
  1353. elif _WIFEXITED(sts):
  1354. self.returncode = _WEXITSTATUS(sts)
  1355. else:
  1356. # Should never happen
  1357. raise RuntimeError("Unknown child exit status!")
  1358.  
  1359.  
  1360. def _internal_poll(self, _deadstate=None, _waitpid=os.waitpid,
  1361. _WNOHANG=os.WNOHANG, _os_error=os.error, _ECHILD=errno.ECHILD):
  1362. """Check if child process has terminated. Returns returncode
  1363. attribute.
  1364.  
  1365. This method is called by __del__, so it cannot reference anything
  1366. outside of the local scope (nor can any methods it calls).
  1367.  
  1368. """
  1369. if self.returncode is None:
  1370. try:
  1371. pid, sts = _waitpid(self.pid, _WNOHANG)
  1372. if pid == self.pid:
  1373. self._handle_exitstatus(sts)
  1374. except _os_error as e:
  1375. if _deadstate is not None:
  1376. self.returncode = _deadstate
  1377. if e.errno == _ECHILD:
  1378. # This happens if SIGCLD is set to be ignored or
  1379. # waiting for child processes has otherwise been
  1380. # disabled for our process. This child is dead, we
  1381. # can't get the status.
  1382. # http://bugs.python.org/issue15756
  1383. self.returncode = 0
  1384. return self.returncode
  1385.  
  1386.  
  1387. def wait(self):
  1388. """Wait for child process to terminate. Returns returncode
  1389. attribute."""
  1390. while self.returncode is None:
  1391. try:
  1392. pid, sts = _eintr_retry_call(os.waitpid, self.pid, 0)
  1393. except OSError as e:
  1394. if e.errno != errno.ECHILD:
  1395. raise
  1396. # This happens if SIGCLD is set to be ignored or waiting
  1397. # for child processes has otherwise been disabled for our
  1398. # process. This child is dead, we can't get the status.
  1399. pid = self.pid
  1400. sts = 0
  1401. # Check the pid and loop as waitpid has been known to return
  1402. # 0 even without WNOHANG in odd situations. issue14396.
  1403. if pid == self.pid:
  1404. self._handle_exitstatus(sts)
  1405. return self.returncode
  1406.  
  1407.  
  1408. def _communicate(self, input):
  1409. if self.stdin:
  1410. # Flush stdio buffer. This might block, if the user has
  1411. # been writing to .stdin in an uncontrolled fashion.
  1412. self.stdin.flush()
  1413. if not input:
  1414. self.stdin.close()
  1415.  
  1416. if _has_poll:
  1417. stdout, stderr = self._communicate_with_poll(input)
  1418. else:
  1419. stdout, stderr = self._communicate_with_select(input)
  1420.  
  1421. # All data exchanged. Translate lists into strings.
  1422. if stdout is not None:
  1423. stdout = ''.join(stdout)
  1424. if stderr is not None:
  1425. stderr = ''.join(stderr)
  1426.  
  1427. # Translate newlines, if requested. We cannot let the file
  1428. # object do the translation: It is based on stdio, which is
  1429. # impossible to combine with select (unless forcing no
  1430. # buffering).
  1431. if self.universal_newlines and hasattr(file, 'newlines'):
  1432. if stdout:
  1433. stdout = self._translate_newlines(stdout)
  1434. if stderr:
  1435. stderr = self._translate_newlines(stderr)
  1436.  
  1437. self.wait()
  1438. return (stdout, stderr)
  1439.  
  1440.  
  1441. def _communicate_with_poll(self, input):
  1442. stdout = None # Return
  1443. stderr = None # Return
  1444. fd2file = {}
  1445. fd2output = {}
  1446.  
  1447. poller = select.poll()
  1448. def register_and_append(file_obj, eventmask):
  1449. poller.register(file_obj.fileno(), eventmask)
  1450. fd2file[file_obj.fileno()] = file_obj
  1451.  
  1452. def close_unregister_and_remove(fd):
  1453. poller.unregister(fd)
  1454. fd2file[fd].close()
  1455. fd2file.pop(fd)
  1456.  
  1457. if self.stdin and input:
  1458. register_and_append(self.stdin, select.POLLOUT)
  1459.  
  1460. select_POLLIN_POLLPRI = select.POLLIN | select.POLLPRI
  1461. if self.stdout:
  1462. register_and_append(self.stdout, select_POLLIN_POLLPRI)
  1463. fd2output[self.stdout.fileno()] = stdout = []
  1464. if self.stderr:
  1465. register_and_append(self.stderr, select_POLLIN_POLLPRI)
  1466. fd2output[self.stderr.fileno()] = stderr = []
  1467.  
  1468. input_offset = 0
  1469. while fd2file:
  1470. try:
  1471. ready = poller.poll()
  1472. except select.error, e:
  1473. if e.args[0] == errno.EINTR:
  1474. continue
  1475. raise
  1476.  
  1477. for fd, mode in ready:
  1478. if mode & select.POLLOUT:
  1479. chunk = input[input_offset : input_offset + _PIPE_BUF]
  1480. try:
  1481. input_offset += os.write(fd, chunk)
  1482. except OSError as e:
  1483. if e.errno == errno.EPIPE:
  1484. close_unregister_and_remove(fd)
  1485. else:
  1486. raise
  1487. else:
  1488. if input_offset >= len(input):
  1489. close_unregister_and_remove(fd)
  1490. elif mode & select_POLLIN_POLLPRI:
  1491. data = os.read(fd, 4096)
  1492. if not data:
  1493. close_unregister_and_remove(fd)
  1494. fd2output[fd].append(data)
  1495. else:
  1496. # Ignore hang up or errors.
  1497. close_unregister_and_remove(fd)
  1498.  
  1499. return (stdout, stderr)
  1500.  
  1501.  
  1502. def _communicate_with_select(self, input):
  1503. read_set = []
  1504. write_set = []
  1505. stdout = None # Return
  1506. stderr = None # Return
  1507.  
  1508. if self.stdin and input:
  1509. write_set.append(self.stdin)
  1510. if self.stdout:
  1511. read_set.append(self.stdout)
  1512. stdout = []
  1513. if self.stderr:
  1514. read_set.append(self.stderr)
  1515. stderr = []
  1516.  
  1517. input_offset = 0
  1518. while read_set or write_set:
  1519. try:
  1520. rlist, wlist, xlist = select.select(read_set, write_set, [])
  1521. except select.error, e:
  1522. if e.args[0] == errno.EINTR:
  1523. continue
  1524. raise
  1525.  
  1526. if self.stdin in wlist:
  1527. chunk = input[input_offset : input_offset + _PIPE_BUF]
  1528. try:
  1529. bytes_written = os.write(self.stdin.fileno(), chunk)
  1530. except OSError as e:
  1531. if e.errno == errno.EPIPE:
  1532. self.stdin.close()
  1533. write_set.remove(self.stdin)
  1534. else:
  1535. raise
  1536. else:
  1537. input_offset += bytes_written
  1538. if input_offset >= len(input):
  1539. self.stdin.close()
  1540. write_set.remove(self.stdin)
  1541.  
  1542. if self.stdout in rlist:
  1543. data = os.read(self.stdout.fileno(), 1024)
  1544. if data == "":
  1545. self.stdout.close()
  1546. read_set.remove(self.stdout)
  1547. stdout.append(data)
  1548.  
  1549. if self.stderr in rlist:
  1550. data = os.read(self.stderr.fileno(), 1024)
  1551. if data == "":
  1552. self.stderr.close()
  1553. read_set.remove(self.stderr)
  1554. stderr.append(data)
  1555.  
  1556. return (stdout, stderr)
  1557.  
  1558.  
  1559. def send_signal(self, sig):
  1560. """Send a signal to the process
  1561. """
  1562. os.kill(self.pid, sig)
  1563.  
  1564. def terminate(self):
  1565. """Terminate the process with SIGTERM
  1566. """
  1567. self.send_signal(signal.SIGTERM)
  1568.  
  1569. def kill(self):
  1570. """Kill the process with SIGKILL
  1571. """
  1572. self.send_signal(signal.SIGKILL)
  1573.  
  1574.  
  1575. def _demo_posix():
  1576. #
  1577. # Example 1: Simple redirection: Get process list
  1578. #
  1579. plist = Popen(["ps"], stdout=PIPE).communicate()[0]
  1580. print "Process list:"
  1581. print plist
  1582.  
  1583. #
  1584. # Example 2: Change uid before executing child
  1585. #
  1586. if os.getuid() == 0:
  1587. p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
  1588. p.wait()
  1589.  
  1590. #
  1591. # Example 3: Connecting several subprocesses
  1592. #
  1593. print "Looking for 'hda'..."
  1594. p1 = Popen(["dmesg"], stdout=PIPE)
  1595. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  1596. print repr(p2.communicate()[0])
  1597.  
  1598. #
  1599. # Example 4: Catch execution error
  1600. #
  1601. print
  1602. print "Trying a weird file..."
  1603. try:
  1604. print Popen(["/this/path/does/not/exist"]).communicate()
  1605. except OSError, e:
  1606. if e.errno == errno.ENOENT:
  1607. print "The file didn't exist. I thought so..."
  1608. print "Child traceback:"
  1609. print e.child_traceback
  1610. else:
  1611. print "Error", e.errno
  1612. else:
  1613. print >>sys.stderr, "Gosh. No error."
  1614.  
  1615.  
  1616. def _demo_windows():
  1617. #
  1618. # Example 1: Connecting several subprocesses
  1619. #
  1620. print "Looking for 'PROMPT' in set output..."
  1621. p1 = Popen("set", stdout=PIPE, shell=True)
  1622. p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
  1623. print repr(p2.communicate()[0])
  1624.  
  1625. #
  1626. # Example 2: Simple execution of program
  1627. #
  1628. print "Executing calc..."
  1629. p = Popen("calc")
  1630. p.wait()
  1631.  
  1632.  
  1633. if __name__ == "__main__":
  1634. if mswindows:
  1635. _demo_windows()
  1636. else:
  1637. _demo_posix()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement