subprocess.py 58 KB

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