PageRenderTime 41ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 1ms

/couchjs/scons/scons-local-2.0.1/SCons/compat/_scons_subprocess.py

http://github.com/cloudant/bigcouch
Python | 1281 lines | 1077 code | 71 blank | 133 comment | 105 complexity | 4b44f485c30fe69e869b6732fc21bd4c MD5 | raw file
Possible License(s): Apache-2.0
  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 two 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. Exceptions
  99. ----------
  100. Exceptions raised in the child process, before the new program has
  101. started to execute, will be re-raised in the parent. Additionally,
  102. the exception object will have one extra attribute called
  103. 'child_traceback', which is a string containing traceback information
  104. from the childs point of view.
  105. The most common exception raised is OSError. This occurs, for
  106. example, when trying to execute a non-existent file. Applications
  107. should prepare for OSErrors.
  108. A ValueError will be raised if Popen is called with invalid arguments.
  109. check_call() will raise CalledProcessError, if the called process
  110. returns a non-zero return code.
  111. Security
  112. --------
  113. Unlike some other popen functions, this implementation will never call
  114. /bin/sh implicitly. This means that all characters, including shell
  115. metacharacters, can safely be passed to child processes.
  116. Popen objects
  117. =============
  118. Instances of the Popen class have the following methods:
  119. poll()
  120. Check if child process has terminated. Returns returncode
  121. attribute.
  122. wait()
  123. Wait for child process to terminate. Returns returncode attribute.
  124. communicate(input=None)
  125. Interact with process: Send data to stdin. Read data from stdout
  126. and stderr, until end-of-file is reached. Wait for process to
  127. terminate. The optional stdin argument should be a string to be
  128. sent to the child process, or None, if no data should be sent to
  129. the child.
  130. communicate() returns a tuple (stdout, stderr).
  131. Note: The data read is buffered in memory, so do not use this
  132. method if the data size is large or unlimited.
  133. The following attributes are also available:
  134. stdin
  135. If the stdin argument is PIPE, this attribute is a file object
  136. that provides input to the child process. Otherwise, it is None.
  137. stdout
  138. If the stdout argument is PIPE, this attribute is a file object
  139. that provides output from the child process. Otherwise, it is
  140. None.
  141. stderr
  142. If the stderr argument is PIPE, this attribute is file object that
  143. provides error output from the child process. Otherwise, it is
  144. None.
  145. pid
  146. The process ID of the child process.
  147. returncode
  148. The child return code. A None value indicates that the process
  149. hasn't terminated yet. A negative value -N indicates that the
  150. child was terminated by signal N (UNIX only).
  151. Replacing older functions with the subprocess module
  152. ====================================================
  153. In this section, "a ==> b" means that b can be used as a replacement
  154. for a.
  155. Note: All functions in this section fail (more or less) silently if
  156. the executed program cannot be found; this module raises an OSError
  157. exception.
  158. In the following examples, we assume that the subprocess module is
  159. imported with "from subprocess import *".
  160. Replacing /bin/sh shell backquote
  161. ---------------------------------
  162. output=`mycmd myarg`
  163. ==>
  164. output = Popen(["mycmd", "myarg"], stdout=PIPE).communicate()[0]
  165. Replacing shell pipe line
  166. -------------------------
  167. output=`dmesg | grep hda`
  168. ==>
  169. p1 = Popen(["dmesg"], stdout=PIPE)
  170. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  171. output = p2.communicate()[0]
  172. Replacing os.system()
  173. ---------------------
  174. sts = os.system("mycmd" + " myarg")
  175. ==>
  176. p = Popen("mycmd" + " myarg", shell=True)
  177. pid, sts = os.waitpid(p.pid, 0)
  178. Note:
  179. * Calling the program through the shell is usually not required.
  180. * It's easier to look at the returncode attribute than the
  181. exitstatus.
  182. A more real-world example would look like this:
  183. try:
  184. retcode = call("mycmd" + " myarg", shell=True)
  185. if retcode < 0:
  186. print >>sys.stderr, "Child was terminated by signal", -retcode
  187. else:
  188. print >>sys.stderr, "Child returned", retcode
  189. except OSError, e:
  190. print >>sys.stderr, "Execution failed:", e
  191. Replacing os.spawn*
  192. -------------------
  193. P_NOWAIT example:
  194. pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
  195. ==>
  196. pid = Popen(["/bin/mycmd", "myarg"]).pid
  197. P_WAIT example:
  198. retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
  199. ==>
  200. retcode = call(["/bin/mycmd", "myarg"])
  201. Vector example:
  202. os.spawnvp(os.P_NOWAIT, path, args)
  203. ==>
  204. Popen([path] + args[1:])
  205. Environment example:
  206. os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env)
  207. ==>
  208. Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"})
  209. Replacing os.popen*
  210. -------------------
  211. pipe = os.popen(cmd, mode='r', bufsize)
  212. ==>
  213. pipe = Popen(cmd, shell=True, bufsize=bufsize, stdout=PIPE).stdout
  214. pipe = os.popen(cmd, mode='w', bufsize)
  215. ==>
  216. pipe = Popen(cmd, shell=True, bufsize=bufsize, stdin=PIPE).stdin
  217. (child_stdin, child_stdout) = os.popen2(cmd, mode, bufsize)
  218. ==>
  219. p = Popen(cmd, shell=True, bufsize=bufsize,
  220. stdin=PIPE, stdout=PIPE, close_fds=True)
  221. (child_stdin, child_stdout) = (p.stdin, p.stdout)
  222. (child_stdin,
  223. child_stdout,
  224. child_stderr) = os.popen3(cmd, mode, bufsize)
  225. ==>
  226. p = Popen(cmd, shell=True, bufsize=bufsize,
  227. stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True)
  228. (child_stdin,
  229. child_stdout,
  230. child_stderr) = (p.stdin, p.stdout, p.stderr)
  231. (child_stdin, child_stdout_and_stderr) = os.popen4(cmd, mode, bufsize)
  232. ==>
  233. p = Popen(cmd, shell=True, bufsize=bufsize,
  234. stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
  235. (child_stdin, child_stdout_and_stderr) = (p.stdin, p.stdout)
  236. Replacing popen2.*
  237. ------------------
  238. Note: If the cmd argument to popen2 functions is a string, the command
  239. is executed through /bin/sh. If it is a list, the command is directly
  240. executed.
  241. (child_stdout, child_stdin) = popen2.popen2("somestring", bufsize, mode)
  242. ==>
  243. p = Popen(["somestring"], shell=True, bufsize=bufsize
  244. stdin=PIPE, stdout=PIPE, close_fds=True)
  245. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  246. (child_stdout, child_stdin) = popen2.popen2(["mycmd", "myarg"], bufsize, mode)
  247. ==>
  248. p = Popen(["mycmd", "myarg"], bufsize=bufsize,
  249. stdin=PIPE, stdout=PIPE, close_fds=True)
  250. (child_stdout, child_stdin) = (p.stdout, p.stdin)
  251. The popen2.Popen3 and popen3.Popen4 basically works as subprocess.Popen,
  252. except that:
  253. * subprocess.Popen raises an exception if the execution fails
  254. * the capturestderr argument is replaced with the stderr argument.
  255. * stdin=PIPE and stdout=PIPE must be specified.
  256. * popen2 closes all filedescriptors by default, but you have to specify
  257. close_fds=True with subprocess.Popen.
  258. """
  259. import sys
  260. mswindows = (sys.platform == "win32")
  261. import os
  262. import types
  263. import traceback
  264. # Exception classes used by this module.
  265. class CalledProcessError(Exception):
  266. """This exception is raised when a process run by check_call() returns
  267. a non-zero exit status. The exit status will be stored in the
  268. returncode attribute."""
  269. def __init__(self, returncode, cmd):
  270. self.returncode = returncode
  271. self.cmd = cmd
  272. def __str__(self):
  273. return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
  274. if mswindows:
  275. try:
  276. import threading
  277. except ImportError:
  278. # SCons: the threading module is only used by the communicate()
  279. # method, which we don't actually use, so don't worry if we
  280. # can't import it.
  281. pass
  282. import msvcrt
  283. try:
  284. # Try to get _subprocess
  285. from _subprocess import *
  286. class STARTUPINFO(object):
  287. dwFlags = 0
  288. hStdInput = None
  289. hStdOutput = None
  290. hStdError = None
  291. wShowWindow = 0
  292. class pywintypes(object):
  293. error = IOError
  294. except ImportError:
  295. # If not there, then drop back to requiring pywin32
  296. # TODO: Should this be wrapped in try as well? To notify user to install
  297. # pywin32 ? With URL to it?
  298. import pywintypes
  299. from win32api import GetStdHandle, STD_INPUT_HANDLE, \
  300. STD_OUTPUT_HANDLE, STD_ERROR_HANDLE
  301. from win32api import GetCurrentProcess, DuplicateHandle, \
  302. GetModuleFileName, GetVersion
  303. from win32con import DUPLICATE_SAME_ACCESS, SW_HIDE
  304. from win32pipe import CreatePipe
  305. from win32process import CreateProcess, STARTUPINFO, \
  306. GetExitCodeProcess, STARTF_USESTDHANDLES, \
  307. STARTF_USESHOWWINDOW, CREATE_NEW_CONSOLE
  308. from win32event import WaitForSingleObject, INFINITE, WAIT_OBJECT_0
  309. else:
  310. import select
  311. import errno
  312. import fcntl
  313. import pickle
  314. try:
  315. fcntl.F_GETFD
  316. except AttributeError:
  317. fcntl.F_GETFD = 1
  318. try:
  319. fcntl.F_SETFD
  320. except AttributeError:
  321. fcntl.F_SETFD = 2
  322. __all__ = ["Popen", "PIPE", "STDOUT", "call", "check_call", "CalledProcessError"]
  323. try:
  324. MAXFD = os.sysconf("SC_OPEN_MAX")
  325. except KeyboardInterrupt:
  326. raise # SCons: don't swallow keyboard interrupts
  327. except:
  328. MAXFD = 256
  329. try:
  330. isinstance(1, int)
  331. except TypeError:
  332. def is_int(obj):
  333. return isinstance(obj, type(1))
  334. def is_int_or_long(obj):
  335. return type(obj) in (type(1), type(1L))
  336. else:
  337. def is_int(obj):
  338. return isinstance(obj, int)
  339. def is_int_or_long(obj):
  340. return isinstance(obj, (int, long))
  341. try:
  342. types.StringTypes
  343. except AttributeError:
  344. try:
  345. types.StringTypes = (str, unicode)
  346. except NameError:
  347. types.StringTypes = (str,)
  348. def is_string(obj):
  349. return isinstance(obj, types.StringTypes)
  350. _active = []
  351. def _cleanup():
  352. for inst in _active[:]:
  353. if inst.poll(_deadstate=sys.maxsize) >= 0:
  354. try:
  355. _active.remove(inst)
  356. except ValueError:
  357. # This can happen if two threads create a new Popen instance.
  358. # It's harmless that it was already removed, so ignore.
  359. pass
  360. PIPE = -1
  361. STDOUT = -2
  362. def call(*popenargs, **kwargs):
  363. """Run command with arguments. Wait for command to complete, then
  364. return the returncode attribute.
  365. The arguments are the same as for the Popen constructor. Example:
  366. retcode = call(["ls", "-l"])
  367. """
  368. return apply(Popen, popenargs, kwargs).wait()
  369. def check_call(*popenargs, **kwargs):
  370. """Run command with arguments. Wait for command to complete. If
  371. the exit code was zero then return, otherwise raise
  372. CalledProcessError. The CalledProcessError object will have the
  373. return code in the returncode attribute.
  374. The arguments are the same as for the Popen constructor. Example:
  375. check_call(["ls", "-l"])
  376. """
  377. retcode = call(*popenargs, **kwargs)
  378. cmd = kwargs.get("args")
  379. if cmd is None:
  380. cmd = popenargs[0]
  381. if retcode:
  382. raise CalledProcessError(retcode, cmd)
  383. return retcode
  384. def list2cmdline(seq):
  385. """
  386. Translate a sequence of arguments into a command line
  387. string, using the same rules as the MS C runtime:
  388. 1) Arguments are delimited by white space, which is either a
  389. space or a tab.
  390. 2) A string surrounded by double quotation marks is
  391. interpreted as a single argument, regardless of white space
  392. contained within. A quoted string can be embedded in an
  393. argument.
  394. 3) A double quotation mark preceded by a backslash is
  395. interpreted as a literal double quotation mark.
  396. 4) Backslashes are interpreted literally, unless they
  397. immediately precede a double quotation mark.
  398. 5) If backslashes immediately precede a double quotation mark,
  399. every pair of backslashes is interpreted as a literal
  400. backslash. If the number of backslashes is odd, the last
  401. backslash escapes the next double quotation mark as
  402. described in rule 3.
  403. """
  404. # See
  405. # http://msdn.microsoft.com/library/en-us/vccelng/htm/progs_12.asp
  406. result = []
  407. needquote = False
  408. for arg in seq:
  409. bs_buf = []
  410. # Add a space to separate this argument from the others
  411. if result:
  412. result.append(' ')
  413. needquote = (" " in arg) or ("\t" in arg)
  414. if needquote:
  415. result.append('"')
  416. for c in arg:
  417. if c == '\\':
  418. # Don't know if we need to double yet.
  419. bs_buf.append(c)
  420. elif c == '"':
  421. # Double backspaces.
  422. result.append('\\' * len(bs_buf)*2)
  423. bs_buf = []
  424. result.append('\\"')
  425. else:
  426. # Normal char
  427. if bs_buf:
  428. result.extend(bs_buf)
  429. bs_buf = []
  430. result.append(c)
  431. # Add remaining backspaces, if any.
  432. if bs_buf:
  433. result.extend(bs_buf)
  434. if needquote:
  435. result.extend(bs_buf)
  436. result.append('"')
  437. return ''.join(result)
  438. class Popen(object):
  439. def __init__(self, args, bufsize=0, executable=None,
  440. stdin=None, stdout=None, stderr=None,
  441. preexec_fn=None, close_fds=False, shell=False,
  442. cwd=None, env=None, universal_newlines=False,
  443. startupinfo=None, creationflags=0):
  444. """Create new Popen instance."""
  445. _cleanup()
  446. self._child_created = False
  447. if not is_int_or_long(bufsize):
  448. raise TypeError("bufsize must be an integer")
  449. if mswindows:
  450. if preexec_fn is not None:
  451. raise ValueError("preexec_fn is not supported on Windows "
  452. "platforms")
  453. if close_fds:
  454. raise ValueError("close_fds is not supported on Windows "
  455. "platforms")
  456. else:
  457. # POSIX
  458. if startupinfo is not None:
  459. raise ValueError("startupinfo is only supported on Windows "
  460. "platforms")
  461. if creationflags != 0:
  462. raise ValueError("creationflags is only supported on Windows "
  463. "platforms")
  464. self.stdin = None
  465. self.stdout = None
  466. self.stderr = None
  467. self.pid = None
  468. self.returncode = None
  469. self.universal_newlines = universal_newlines
  470. # Input and output objects. The general principle is like
  471. # this:
  472. #
  473. # Parent Child
  474. # ------ -----
  475. # p2cwrite ---stdin---> p2cread
  476. # c2pread <--stdout--- c2pwrite
  477. # errread <--stderr--- errwrite
  478. #
  479. # On POSIX, the child objects are file descriptors. On
  480. # Windows, these are Windows file handles. The parent objects
  481. # are file descriptors on both platforms. The parent objects
  482. # are None when not using PIPEs. The child objects are None
  483. # when not redirecting.
  484. (p2cread, p2cwrite,
  485. c2pread, c2pwrite,
  486. errread, errwrite) = self._get_handles(stdin, stdout, stderr)
  487. self._execute_child(args, executable, preexec_fn, close_fds,
  488. cwd, env, universal_newlines,
  489. startupinfo, creationflags, shell,
  490. p2cread, p2cwrite,
  491. c2pread, c2pwrite,
  492. errread, errwrite)
  493. if p2cwrite:
  494. self.stdin = os.fdopen(p2cwrite, 'wb', bufsize)
  495. if c2pread:
  496. if universal_newlines:
  497. self.stdout = os.fdopen(c2pread, 'rU', bufsize)
  498. else:
  499. self.stdout = os.fdopen(c2pread, 'rb', bufsize)
  500. if errread:
  501. if universal_newlines:
  502. self.stderr = os.fdopen(errread, 'rU', bufsize)
  503. else:
  504. self.stderr = os.fdopen(errread, 'rb', bufsize)
  505. def _translate_newlines(self, data):
  506. data = data.replace("\r\n", "\n")
  507. data = data.replace("\r", "\n")
  508. return data
  509. def __del__(self):
  510. if not self._child_created:
  511. # We didn't get to successfully create a child process.
  512. return
  513. # In case the child hasn't been waited on, check if it's done.
  514. self.poll(_deadstate=sys.maxsize)
  515. if self.returncode is None and _active is not None:
  516. # Child is still running, keep us alive until we can wait on it.
  517. _active.append(self)
  518. def communicate(self, input=None):
  519. """Interact with process: Send data to stdin. Read data from
  520. stdout and stderr, until end-of-file is reached. Wait for
  521. process to terminate. The optional input argument should be a
  522. string to be sent to the child process, or None, if no data
  523. should be sent to the child.
  524. communicate() returns a tuple (stdout, stderr)."""
  525. # Optimization: If we are only using one pipe, or no pipe at
  526. # all, using select() or threads is unnecessary.
  527. if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
  528. stdout = None
  529. stderr = None
  530. if self.stdin:
  531. if input:
  532. self.stdin.write(input)
  533. self.stdin.close()
  534. elif self.stdout:
  535. stdout = self.stdout.read()
  536. elif self.stderr:
  537. stderr = self.stderr.read()
  538. self.wait()
  539. return (stdout, stderr)
  540. return self._communicate(input)
  541. if mswindows:
  542. #
  543. # Windows methods
  544. #
  545. def _get_handles(self, stdin, stdout, stderr):
  546. """Construct and return tupel with IO objects:
  547. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  548. """
  549. if stdin is None and stdout is None and stderr is None:
  550. return (None, None, None, None, None, None)
  551. p2cread, p2cwrite = None, None
  552. c2pread, c2pwrite = None, None
  553. errread, errwrite = None, None
  554. if stdin is None:
  555. p2cread = GetStdHandle(STD_INPUT_HANDLE)
  556. elif stdin == PIPE:
  557. p2cread, p2cwrite = CreatePipe(None, 0)
  558. # Detach and turn into fd
  559. p2cwrite = p2cwrite.Detach()
  560. p2cwrite = msvcrt.open_osfhandle(p2cwrite, 0)
  561. elif is_int(stdin):
  562. p2cread = msvcrt.get_osfhandle(stdin)
  563. else:
  564. # Assuming file-like object
  565. p2cread = msvcrt.get_osfhandle(stdin.fileno())
  566. p2cread = self._make_inheritable(p2cread)
  567. if stdout is None:
  568. c2pwrite = GetStdHandle(STD_OUTPUT_HANDLE)
  569. elif stdout == PIPE:
  570. c2pread, c2pwrite = CreatePipe(None, 0)
  571. # Detach and turn into fd
  572. c2pread = c2pread.Detach()
  573. c2pread = msvcrt.open_osfhandle(c2pread, 0)
  574. elif is_int(stdout):
  575. c2pwrite = msvcrt.get_osfhandle(stdout)
  576. else:
  577. # Assuming file-like object
  578. c2pwrite = msvcrt.get_osfhandle(stdout.fileno())
  579. c2pwrite = self._make_inheritable(c2pwrite)
  580. if stderr is None:
  581. errwrite = GetStdHandle(STD_ERROR_HANDLE)
  582. elif stderr == PIPE:
  583. errread, errwrite = CreatePipe(None, 0)
  584. # Detach and turn into fd
  585. errread = errread.Detach()
  586. errread = msvcrt.open_osfhandle(errread, 0)
  587. elif stderr == STDOUT:
  588. errwrite = c2pwrite
  589. elif is_int(stderr):
  590. errwrite = msvcrt.get_osfhandle(stderr)
  591. else:
  592. # Assuming file-like object
  593. errwrite = msvcrt.get_osfhandle(stderr.fileno())
  594. errwrite = self._make_inheritable(errwrite)
  595. return (p2cread, p2cwrite,
  596. c2pread, c2pwrite,
  597. errread, errwrite)
  598. def _make_inheritable(self, handle):
  599. """Return a duplicate of handle, which is inheritable"""
  600. return DuplicateHandle(GetCurrentProcess(), handle,
  601. GetCurrentProcess(), 0, 1,
  602. DUPLICATE_SAME_ACCESS)
  603. def _find_w9xpopen(self):
  604. """Find and return absolut path to w9xpopen.exe"""
  605. w9xpopen = os.path.join(os.path.dirname(GetModuleFileName(0)),
  606. "w9xpopen.exe")
  607. if not os.path.exists(w9xpopen):
  608. # Eeek - file-not-found - possibly an embedding
  609. # situation - see if we can locate it in sys.exec_prefix
  610. w9xpopen = os.path.join(os.path.dirname(sys.exec_prefix),
  611. "w9xpopen.exe")
  612. if not os.path.exists(w9xpopen):
  613. raise RuntimeError("Cannot locate w9xpopen.exe, which is "
  614. "needed for Popen to work with your "
  615. "shell or platform.")
  616. return w9xpopen
  617. def _execute_child(self, args, executable, preexec_fn, close_fds,
  618. cwd, env, universal_newlines,
  619. startupinfo, creationflags, shell,
  620. p2cread, p2cwrite,
  621. c2pread, c2pwrite,
  622. errread, errwrite):
  623. """Execute program (MS Windows version)"""
  624. if not isinstance(args, types.StringTypes):
  625. args = list2cmdline(args)
  626. # Process startup details
  627. if startupinfo is None:
  628. startupinfo = STARTUPINFO()
  629. if None not in (p2cread, c2pwrite, errwrite):
  630. startupinfo.dwFlags = startupinfo.dwFlags | STARTF_USESTDHANDLES
  631. startupinfo.hStdInput = p2cread
  632. startupinfo.hStdOutput = c2pwrite
  633. startupinfo.hStdError = errwrite
  634. if shell:
  635. startupinfo.dwFlags = startupinfo.dwFlags | STARTF_USESHOWWINDOW
  636. startupinfo.wShowWindow = SW_HIDE
  637. comspec = os.environ.get("COMSPEC", "cmd.exe")
  638. args = comspec + " /c " + args
  639. if (GetVersion() >= 0x80000000L or
  640. os.path.basename(comspec).lower() == "command.com"):
  641. # Win9x, or using command.com on NT. We need to
  642. # use the w9xpopen intermediate program. For more
  643. # information, see KB Q150956
  644. # (http://web.archive.org/web/20011105084002/http://support.microsoft.com/support/kb/articles/Q150/9/56.asp)
  645. w9xpopen = self._find_w9xpopen()
  646. args = '"%s" %s' % (w9xpopen, args)
  647. # Not passing CREATE_NEW_CONSOLE has been known to
  648. # cause random failures on win9x. Specifically a
  649. # dialog: "Your program accessed mem currently in
  650. # use at xxx" and a hopeful warning about the
  651. # stability of your system. Cost is Ctrl+C wont
  652. # kill children.
  653. creationflags = creationflags | CREATE_NEW_CONSOLE
  654. # Start the process
  655. try:
  656. hp, ht, pid, tid = CreateProcess(executable, args,
  657. # no special security
  658. None, None,
  659. # must inherit handles to pass std
  660. # handles
  661. 1,
  662. creationflags,
  663. env,
  664. cwd,
  665. startupinfo)
  666. except pywintypes.error, e:
  667. # Translate pywintypes.error to WindowsError, which is
  668. # a subclass of OSError. FIXME: We should really
  669. # translate errno using _sys_errlist (or simliar), but
  670. # how can this be done from Python?
  671. raise WindowsError(*e.args)
  672. # Retain the process handle, but close the thread handle
  673. self._child_created = True
  674. self._handle = hp
  675. self.pid = pid
  676. ht.Close()
  677. # Child is launched. Close the parent's copy of those pipe
  678. # handles that only the child should have open. You need
  679. # to make sure that no handles to the write end of the
  680. # output pipe are maintained in this process or else the
  681. # pipe will not close when the child process exits and the
  682. # ReadFile will hang.
  683. if p2cread is not None:
  684. p2cread.Close()
  685. if c2pwrite is not None:
  686. c2pwrite.Close()
  687. if errwrite is not None:
  688. errwrite.Close()
  689. def poll(self, _deadstate=None):
  690. """Check if child process has terminated. Returns returncode
  691. attribute."""
  692. if self.returncode is None:
  693. if WaitForSingleObject(self._handle, 0) == WAIT_OBJECT_0:
  694. self.returncode = GetExitCodeProcess(self._handle)
  695. return self.returncode
  696. def wait(self):
  697. """Wait for child process to terminate. Returns returncode
  698. attribute."""
  699. if self.returncode is None:
  700. obj = WaitForSingleObject(self._handle, INFINITE)
  701. self.returncode = GetExitCodeProcess(self._handle)
  702. return self.returncode
  703. def _readerthread(self, fh, buffer):
  704. buffer.append(fh.read())
  705. def _communicate(self, input):
  706. stdout = None # Return
  707. stderr = None # Return
  708. if self.stdout:
  709. stdout = []
  710. stdout_thread = threading.Thread(target=self._readerthread,
  711. args=(self.stdout, stdout))
  712. stdout_thread.setDaemon(True)
  713. stdout_thread.start()
  714. if self.stderr:
  715. stderr = []
  716. stderr_thread = threading.Thread(target=self._readerthread,
  717. args=(self.stderr, stderr))
  718. stderr_thread.setDaemon(True)
  719. stderr_thread.start()
  720. if self.stdin:
  721. if input is not None:
  722. self.stdin.write(input)
  723. self.stdin.close()
  724. if self.stdout:
  725. stdout_thread.join()
  726. if self.stderr:
  727. stderr_thread.join()
  728. # All data exchanged. Translate lists into strings.
  729. if stdout is not None:
  730. stdout = stdout[0]
  731. if stderr is not None:
  732. stderr = stderr[0]
  733. # Translate newlines, if requested. We cannot let the file
  734. # object do the translation: It is based on stdio, which is
  735. # impossible to combine with select (unless forcing no
  736. # buffering).
  737. if self.universal_newlines and hasattr(file, 'newlines'):
  738. if stdout:
  739. stdout = self._translate_newlines(stdout)
  740. if stderr:
  741. stderr = self._translate_newlines(stderr)
  742. self.wait()
  743. return (stdout, stderr)
  744. else:
  745. #
  746. # POSIX methods
  747. #
  748. def _get_handles(self, stdin, stdout, stderr):
  749. """Construct and return tupel with IO objects:
  750. p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite
  751. """
  752. p2cread, p2cwrite = None, None
  753. c2pread, c2pwrite = None, None
  754. errread, errwrite = None, None
  755. if stdin is None:
  756. pass
  757. elif stdin == PIPE:
  758. p2cread, p2cwrite = os.pipe()
  759. elif is_int(stdin):
  760. p2cread = stdin
  761. else:
  762. # Assuming file-like object
  763. p2cread = stdin.fileno()
  764. if stdout is None:
  765. pass
  766. elif stdout == PIPE:
  767. c2pread, c2pwrite = os.pipe()
  768. elif is_int(stdout):
  769. c2pwrite = stdout
  770. else:
  771. # Assuming file-like object
  772. c2pwrite = stdout.fileno()
  773. if stderr is None:
  774. pass
  775. elif stderr == PIPE:
  776. errread, errwrite = os.pipe()
  777. elif stderr == STDOUT:
  778. errwrite = c2pwrite
  779. elif is_int(stderr):
  780. errwrite = stderr
  781. else:
  782. # Assuming file-like object
  783. errwrite = stderr.fileno()
  784. return (p2cread, p2cwrite,
  785. c2pread, c2pwrite,
  786. errread, errwrite)
  787. def _set_cloexec_flag(self, fd):
  788. try:
  789. cloexec_flag = fcntl.FD_CLOEXEC
  790. except AttributeError:
  791. cloexec_flag = 1
  792. old = fcntl.fcntl(fd, fcntl.F_GETFD)
  793. fcntl.fcntl(fd, fcntl.F_SETFD, old | cloexec_flag)
  794. def _close_fds(self, but):
  795. for i in range(3, MAXFD):
  796. if i == but:
  797. continue
  798. try:
  799. os.close(i)
  800. except KeyboardInterrupt:
  801. raise # SCons: don't swallow keyboard interrupts
  802. except:
  803. pass
  804. def _execute_child(self, args, executable, preexec_fn, close_fds,
  805. cwd, env, universal_newlines,
  806. startupinfo, creationflags, shell,
  807. p2cread, p2cwrite,
  808. c2pread, c2pwrite,
  809. errread, errwrite):
  810. """Execute program (POSIX version)"""
  811. if is_string(args):
  812. args = [args]
  813. if shell:
  814. args = ["/bin/sh", "-c"] + args
  815. if executable is None:
  816. executable = args[0]
  817. # For transferring possible exec failure from child to parent
  818. # The first char specifies the exception type: 0 means
  819. # OSError, 1 means some other error.
  820. errpipe_read, errpipe_write = os.pipe()
  821. self._set_cloexec_flag(errpipe_write)
  822. self.pid = os.fork()
  823. self._child_created = True
  824. if self.pid == 0:
  825. # Child
  826. try:
  827. # Close parent's pipe ends
  828. if p2cwrite:
  829. os.close(p2cwrite)
  830. if c2pread:
  831. os.close(c2pread)
  832. if errread:
  833. os.close(errread)
  834. os.close(errpipe_read)
  835. # Dup fds for child
  836. if p2cread:
  837. os.dup2(p2cread, 0)
  838. if c2pwrite:
  839. os.dup2(c2pwrite, 1)
  840. if errwrite:
  841. os.dup2(errwrite, 2)
  842. # Close pipe fds. Make sure we don't close the same
  843. # fd more than once, or standard fds.
  844. try:
  845. set
  846. except NameError:
  847. # Fall-back for earlier Python versions, so epydoc
  848. # can use this module directly to execute things.
  849. if p2cread:
  850. os.close(p2cread)
  851. if c2pwrite and c2pwrite not in (p2cread,):
  852. os.close(c2pwrite)
  853. if errwrite and errwrite not in (p2cread, c2pwrite):
  854. os.close(errwrite)
  855. else:
  856. for fd in set((p2cread, c2pwrite, errwrite))-set((0,1,2)):
  857. if fd: os.close(fd)
  858. # Close all other fds, if asked for
  859. if close_fds:
  860. self._close_fds(but=errpipe_write)
  861. if cwd is not None:
  862. os.chdir(cwd)
  863. if preexec_fn:
  864. apply(preexec_fn)
  865. if env is None:
  866. os.execvp(executable, args)
  867. else:
  868. os.execvpe(executable, args, env)
  869. except KeyboardInterrupt:
  870. raise # SCons: don't swallow keyboard interrupts
  871. except:
  872. exc_type, exc_value, tb = sys.exc_info()
  873. # Save the traceback and attach it to the exception object
  874. exc_lines = traceback.format_exception(exc_type,
  875. exc_value,
  876. tb)
  877. exc_value.child_traceback = ''.join(exc_lines)
  878. os.write(errpipe_write, pickle.dumps(exc_value))
  879. # This exitcode won't be reported to applications, so it
  880. # really doesn't matter what we return.
  881. os._exit(255)
  882. # Parent
  883. os.close(errpipe_write)
  884. if p2cread and p2cwrite:
  885. os.close(p2cread)
  886. if c2pwrite and c2pread:
  887. os.close(c2pwrite)
  888. if errwrite and errread:
  889. os.close(errwrite)
  890. # Wait for exec to fail or succeed; possibly raising exception
  891. data = os.read(errpipe_read, 1048576) # Exceptions limited to 1 MB
  892. os.close(errpipe_read)
  893. if data != "":
  894. os.waitpid(self.pid, 0)
  895. child_exception = pickle.loads(data)
  896. raise child_exception
  897. def _handle_exitstatus(self, sts):
  898. if os.WIFSIGNALED(sts):
  899. self.returncode = -os.WTERMSIG(sts)
  900. elif os.WIFEXITED(sts):
  901. self.returncode = os.WEXITSTATUS(sts)
  902. else:
  903. # Should never happen
  904. raise RuntimeError("Unknown child exit status!")
  905. def poll(self, _deadstate=None):
  906. """Check if child process has terminated. Returns returncode
  907. attribute."""
  908. if self.returncode is None:
  909. try:
  910. pid, sts = os.waitpid(self.pid, os.WNOHANG)
  911. if pid == self.pid:
  912. self._handle_exitstatus(sts)
  913. except os.error:
  914. if _deadstate is not None:
  915. self.returncode = _deadstate
  916. return self.returncode
  917. def wait(self):
  918. """Wait for child process to terminate. Returns returncode
  919. attribute."""
  920. if self.returncode is None:
  921. pid, sts = os.waitpid(self.pid, 0)
  922. self._handle_exitstatus(sts)
  923. return self.returncode
  924. def _communicate(self, input):
  925. read_set = []
  926. write_set = []
  927. stdout = None # Return
  928. stderr = None # Return
  929. if self.stdin:
  930. # Flush stdio buffer. This might block, if the user has
  931. # been writing to .stdin in an uncontrolled fashion.
  932. self.stdin.flush()
  933. if input:
  934. write_set.append(self.stdin)
  935. else:
  936. self.stdin.close()
  937. if self.stdout:
  938. read_set.append(self.stdout)
  939. stdout = []
  940. if self.stderr:
  941. read_set.append(self.stderr)
  942. stderr = []
  943. input_offset = 0
  944. while read_set or write_set:
  945. rlist, wlist, xlist = select.select(read_set, write_set, [])
  946. if self.stdin in wlist:
  947. # When select has indicated that the file is writable,
  948. # we can write up to PIPE_BUF bytes without risk
  949. # blocking. POSIX defines PIPE_BUF >= 512
  950. m = memoryview(input)[input_offset:input_offset+512]
  951. bytes_written = os.write(self.stdin.fileno(), m)
  952. input_offset = input_offset + bytes_written
  953. if input_offset >= len(input):
  954. self.stdin.close()
  955. write_set.remove(self.stdin)
  956. if self.stdout in rlist:
  957. data = os.read(self.stdout.fileno(), 1024)
  958. if data == "":
  959. self.stdout.close()
  960. read_set.remove(self.stdout)
  961. stdout.append(data)
  962. if self.stderr in rlist:
  963. data = os.read(self.stderr.fileno(), 1024)
  964. if data == "":
  965. self.stderr.close()
  966. read_set.remove(self.stderr)
  967. stderr.append(data)
  968. # All data exchanged. Translate lists into strings.
  969. if stdout is not None:
  970. stdout = ''.join(stdout)
  971. if stderr is not None:
  972. stderr = ''.join(stderr)
  973. # Translate newlines, if requested. We cannot let the file
  974. # object do the translation: It is based on stdio, which is
  975. # impossible to combine with select (unless forcing no
  976. # buffering).
  977. if self.universal_newlines and hasattr(file, 'newlines'):
  978. if stdout:
  979. stdout = self._translate_newlines(stdout)
  980. if stderr:
  981. stderr = self._translate_newlines(stderr)
  982. self.wait()
  983. return (stdout, stderr)
  984. def _demo_posix():
  985. #
  986. # Example 1: Simple redirection: Get process list
  987. #
  988. plist = Popen(["ps"], stdout=PIPE).communicate()[0]
  989. print "Process list:"
  990. print plist
  991. #
  992. # Example 2: Change uid before executing child
  993. #
  994. if os.getuid() == 0:
  995. p = Popen(["id"], preexec_fn=lambda: os.setuid(100))
  996. p.wait()
  997. #
  998. # Example 3: Connecting several subprocesses
  999. #
  1000. print "Looking for 'hda'..."
  1001. p1 = Popen(["dmesg"], stdout=PIPE)
  1002. p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
  1003. print repr(p2.communicate()[0])
  1004. #
  1005. # Example 4: Catch execution error
  1006. #
  1007. print
  1008. print "Trying a weird file..."
  1009. try:
  1010. print Popen(["/this/path/does/not/exist"]).communicate()
  1011. except OSError, e:
  1012. if e.errno == errno.ENOENT:
  1013. print "The file didn't exist. I thought so..."
  1014. print "Child traceback:"
  1015. print e.child_traceback
  1016. else:
  1017. print "Error", e.errno
  1018. else:
  1019. sys.stderr.write( "Gosh. No error.\n" )
  1020. def _demo_windows():
  1021. #
  1022. # Example 1: Connecting several subprocesses
  1023. #
  1024. print "Looking for 'PROMPT' in set output..."
  1025. p1 = Popen("set", stdout=PIPE, shell=True)
  1026. p2 = Popen('find "PROMPT"', stdin=p1.stdout, stdout=PIPE)
  1027. print repr(p2.communicate()[0])
  1028. #
  1029. # Example 2: Simple execution of program
  1030. #
  1031. print "Executing calc..."
  1032. p = Popen("calc")
  1033. p.wait()
  1034. if __name__ == "__main__":
  1035. if mswindows:
  1036. _demo_windows()
  1037. else:
  1038. _demo_posix()
  1039. # Local Variables:
  1040. # tab-width:4
  1041. # indent-tabs-mode:nil
  1042. # End:
  1043. # vim: set expandtab tabstop=4 shiftwidth=4: