subprocess.py 40 KB

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