test_subprocess.py 158 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795
  1. import unittest
  2. from unittest import mock
  3. from test import support
  4. from test.support import import_helper
  5. from test.support import os_helper
  6. from test.support import warnings_helper
  7. import subprocess
  8. import sys
  9. import signal
  10. import io
  11. import itertools
  12. import os
  13. import errno
  14. import tempfile
  15. import time
  16. import traceback
  17. import types
  18. import selectors
  19. import sysconfig
  20. import select
  21. import shutil
  22. import threading
  23. import gc
  24. import textwrap
  25. import json
  26. import pathlib
  27. from test.support.os_helper import FakePath
  28. try:
  29. import _testcapi
  30. except ImportError:
  31. _testcapi = None
  32. try:
  33. import pwd
  34. except ImportError:
  35. pwd = None
  36. try:
  37. import grp
  38. except ImportError:
  39. grp = None
  40. try:
  41. import fcntl
  42. except:
  43. fcntl = None
  44. if support.PGO:
  45. raise unittest.SkipTest("test is not helpful for PGO")
  46. if not support.has_subprocess_support:
  47. raise unittest.SkipTest("test module requires subprocess")
  48. mswindows = (sys.platform == "win32")
  49. #
  50. # Depends on the following external programs: Python
  51. #
  52. if mswindows:
  53. SETBINARY = ('import msvcrt; msvcrt.setmode(sys.stdout.fileno(), '
  54. 'os.O_BINARY);')
  55. else:
  56. SETBINARY = ''
  57. NONEXISTING_CMD = ('nonexisting_i_hope',)
  58. # Ignore errors that indicate the command was not found
  59. NONEXISTING_ERRORS = (FileNotFoundError, NotADirectoryError, PermissionError)
  60. ZERO_RETURN_CMD = (sys.executable, '-c', 'pass')
  61. def setUpModule():
  62. shell_true = shutil.which('true')
  63. if shell_true is None:
  64. return
  65. if (os.access(shell_true, os.X_OK) and
  66. subprocess.run([shell_true]).returncode == 0):
  67. global ZERO_RETURN_CMD
  68. ZERO_RETURN_CMD = (shell_true,) # Faster than Python startup.
  69. class BaseTestCase(unittest.TestCase):
  70. def setUp(self):
  71. # Try to minimize the number of children we have so this test
  72. # doesn't crash on some buildbots (Alphas in particular).
  73. support.reap_children()
  74. def tearDown(self):
  75. if not mswindows:
  76. # subprocess._active is not used on Windows and is set to None.
  77. for inst in subprocess._active:
  78. inst.wait()
  79. subprocess._cleanup()
  80. self.assertFalse(
  81. subprocess._active, "subprocess._active not empty"
  82. )
  83. self.doCleanups()
  84. support.reap_children()
  85. class PopenTestException(Exception):
  86. pass
  87. class PopenExecuteChildRaises(subprocess.Popen):
  88. """Popen subclass for testing cleanup of subprocess.PIPE filehandles when
  89. _execute_child fails.
  90. """
  91. def _execute_child(self, *args, **kwargs):
  92. raise PopenTestException("Forced Exception for Test")
  93. class ProcessTestCase(BaseTestCase):
  94. def test_io_buffered_by_default(self):
  95. p = subprocess.Popen(ZERO_RETURN_CMD,
  96. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  97. stderr=subprocess.PIPE)
  98. try:
  99. self.assertIsInstance(p.stdin, io.BufferedIOBase)
  100. self.assertIsInstance(p.stdout, io.BufferedIOBase)
  101. self.assertIsInstance(p.stderr, io.BufferedIOBase)
  102. finally:
  103. p.stdin.close()
  104. p.stdout.close()
  105. p.stderr.close()
  106. p.wait()
  107. def test_io_unbuffered_works(self):
  108. p = subprocess.Popen(ZERO_RETURN_CMD,
  109. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  110. stderr=subprocess.PIPE, bufsize=0)
  111. try:
  112. self.assertIsInstance(p.stdin, io.RawIOBase)
  113. self.assertIsInstance(p.stdout, io.RawIOBase)
  114. self.assertIsInstance(p.stderr, io.RawIOBase)
  115. finally:
  116. p.stdin.close()
  117. p.stdout.close()
  118. p.stderr.close()
  119. p.wait()
  120. def test_call_seq(self):
  121. # call() function with sequence argument
  122. rc = subprocess.call([sys.executable, "-c",
  123. "import sys; sys.exit(47)"])
  124. self.assertEqual(rc, 47)
  125. def test_call_timeout(self):
  126. # call() function with timeout argument; we want to test that the child
  127. # process gets killed when the timeout expires. If the child isn't
  128. # killed, this call will deadlock since subprocess.call waits for the
  129. # child.
  130. self.assertRaises(subprocess.TimeoutExpired, subprocess.call,
  131. [sys.executable, "-c", "while True: pass"],
  132. timeout=0.1)
  133. def test_check_call_zero(self):
  134. # check_call() function with zero return code
  135. rc = subprocess.check_call(ZERO_RETURN_CMD)
  136. self.assertEqual(rc, 0)
  137. def test_check_call_nonzero(self):
  138. # check_call() function with non-zero return code
  139. with self.assertRaises(subprocess.CalledProcessError) as c:
  140. subprocess.check_call([sys.executable, "-c",
  141. "import sys; sys.exit(47)"])
  142. self.assertEqual(c.exception.returncode, 47)
  143. def test_check_output(self):
  144. # check_output() function with zero return code
  145. output = subprocess.check_output(
  146. [sys.executable, "-c", "print('BDFL')"])
  147. self.assertIn(b'BDFL', output)
  148. with self.assertRaisesRegex(ValueError,
  149. "stdout argument not allowed, it will be overridden"):
  150. subprocess.check_output([], stdout=None)
  151. with self.assertRaisesRegex(ValueError,
  152. "check argument not allowed, it will be overridden"):
  153. subprocess.check_output([], check=False)
  154. def test_check_output_nonzero(self):
  155. # check_call() function with non-zero return code
  156. with self.assertRaises(subprocess.CalledProcessError) as c:
  157. subprocess.check_output(
  158. [sys.executable, "-c", "import sys; sys.exit(5)"])
  159. self.assertEqual(c.exception.returncode, 5)
  160. def test_check_output_stderr(self):
  161. # check_output() function stderr redirected to stdout
  162. output = subprocess.check_output(
  163. [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
  164. stderr=subprocess.STDOUT)
  165. self.assertIn(b'BDFL', output)
  166. def test_check_output_stdin_arg(self):
  167. # check_output() can be called with stdin set to a file
  168. tf = tempfile.TemporaryFile()
  169. self.addCleanup(tf.close)
  170. tf.write(b'pear')
  171. tf.seek(0)
  172. output = subprocess.check_output(
  173. [sys.executable, "-c",
  174. "import sys; sys.stdout.write(sys.stdin.read().upper())"],
  175. stdin=tf)
  176. self.assertIn(b'PEAR', output)
  177. def test_check_output_input_arg(self):
  178. # check_output() can be called with input set to a string
  179. output = subprocess.check_output(
  180. [sys.executable, "-c",
  181. "import sys; sys.stdout.write(sys.stdin.read().upper())"],
  182. input=b'pear')
  183. self.assertIn(b'PEAR', output)
  184. def test_check_output_input_none(self):
  185. """input=None has a legacy meaning of input='' on check_output."""
  186. output = subprocess.check_output(
  187. [sys.executable, "-c",
  188. "import sys; print('XX' if sys.stdin.read() else '')"],
  189. input=None)
  190. self.assertNotIn(b'XX', output)
  191. def test_check_output_input_none_text(self):
  192. output = subprocess.check_output(
  193. [sys.executable, "-c",
  194. "import sys; print('XX' if sys.stdin.read() else '')"],
  195. input=None, text=True)
  196. self.assertNotIn('XX', output)
  197. def test_check_output_input_none_universal_newlines(self):
  198. output = subprocess.check_output(
  199. [sys.executable, "-c",
  200. "import sys; print('XX' if sys.stdin.read() else '')"],
  201. input=None, universal_newlines=True)
  202. self.assertNotIn('XX', output)
  203. def test_check_output_input_none_encoding_errors(self):
  204. output = subprocess.check_output(
  205. [sys.executable, "-c", "print('foo')"],
  206. input=None, encoding='utf-8', errors='ignore')
  207. self.assertIn('foo', output)
  208. def test_check_output_stdout_arg(self):
  209. # check_output() refuses to accept 'stdout' argument
  210. with self.assertRaises(ValueError) as c:
  211. output = subprocess.check_output(
  212. [sys.executable, "-c", "print('will not be run')"],
  213. stdout=sys.stdout)
  214. self.fail("Expected ValueError when stdout arg supplied.")
  215. self.assertIn('stdout', c.exception.args[0])
  216. def test_check_output_stdin_with_input_arg(self):
  217. # check_output() refuses to accept 'stdin' with 'input'
  218. tf = tempfile.TemporaryFile()
  219. self.addCleanup(tf.close)
  220. tf.write(b'pear')
  221. tf.seek(0)
  222. with self.assertRaises(ValueError) as c:
  223. output = subprocess.check_output(
  224. [sys.executable, "-c", "print('will not be run')"],
  225. stdin=tf, input=b'hare')
  226. self.fail("Expected ValueError when stdin and input args supplied.")
  227. self.assertIn('stdin', c.exception.args[0])
  228. self.assertIn('input', c.exception.args[0])
  229. def test_check_output_timeout(self):
  230. # check_output() function with timeout arg
  231. with self.assertRaises(subprocess.TimeoutExpired) as c:
  232. output = subprocess.check_output(
  233. [sys.executable, "-c",
  234. "import sys, time\n"
  235. "sys.stdout.write('BDFL')\n"
  236. "sys.stdout.flush()\n"
  237. "time.sleep(3600)"],
  238. # Some heavily loaded buildbots (sparc Debian 3.x) require
  239. # this much time to start and print.
  240. timeout=3)
  241. self.fail("Expected TimeoutExpired.")
  242. self.assertEqual(c.exception.output, b'BDFL')
  243. def test_call_kwargs(self):
  244. # call() function with keyword args
  245. newenv = os.environ.copy()
  246. newenv["FRUIT"] = "banana"
  247. rc = subprocess.call([sys.executable, "-c",
  248. 'import sys, os;'
  249. 'sys.exit(os.getenv("FRUIT")=="banana")'],
  250. env=newenv)
  251. self.assertEqual(rc, 1)
  252. def test_invalid_args(self):
  253. # Popen() called with invalid arguments should raise TypeError
  254. # but Popen.__del__ should not complain (issue #12085)
  255. with support.captured_stderr() as s:
  256. self.assertRaises(TypeError, subprocess.Popen, invalid_arg_name=1)
  257. argcount = subprocess.Popen.__init__.__code__.co_argcount
  258. too_many_args = [0] * (argcount + 1)
  259. self.assertRaises(TypeError, subprocess.Popen, *too_many_args)
  260. self.assertEqual(s.getvalue(), '')
  261. def test_stdin_none(self):
  262. # .stdin is None when not redirected
  263. p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
  264. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  265. self.addCleanup(p.stdout.close)
  266. self.addCleanup(p.stderr.close)
  267. p.wait()
  268. self.assertEqual(p.stdin, None)
  269. def test_stdout_none(self):
  270. # .stdout is None when not redirected, and the child's stdout will
  271. # be inherited from the parent. In order to test this we run a
  272. # subprocess in a subprocess:
  273. # this_test
  274. # \-- subprocess created by this test (parent)
  275. # \-- subprocess created by the parent subprocess (child)
  276. # The parent doesn't specify stdout, so the child will use the
  277. # parent's stdout. This test checks that the message printed by the
  278. # child goes to the parent stdout. The parent also checks that the
  279. # child's stdout is None. See #11963.
  280. code = ('import sys; from subprocess import Popen, PIPE;'
  281. 'p = Popen([sys.executable, "-c", "print(\'test_stdout_none\')"],'
  282. ' stdin=PIPE, stderr=PIPE);'
  283. 'p.wait(); assert p.stdout is None;')
  284. p = subprocess.Popen([sys.executable, "-c", code],
  285. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  286. self.addCleanup(p.stdout.close)
  287. self.addCleanup(p.stderr.close)
  288. out, err = p.communicate()
  289. self.assertEqual(p.returncode, 0, err)
  290. self.assertEqual(out.rstrip(), b'test_stdout_none')
  291. def test_stderr_none(self):
  292. # .stderr is None when not redirected
  293. p = subprocess.Popen([sys.executable, "-c", 'print("banana")'],
  294. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  295. self.addCleanup(p.stdout.close)
  296. self.addCleanup(p.stdin.close)
  297. p.wait()
  298. self.assertEqual(p.stderr, None)
  299. def _assert_python(self, pre_args, **kwargs):
  300. # We include sys.exit() to prevent the test runner from hanging
  301. # whenever python is found.
  302. args = pre_args + ["import sys; sys.exit(47)"]
  303. p = subprocess.Popen(args, **kwargs)
  304. p.wait()
  305. self.assertEqual(47, p.returncode)
  306. def test_executable(self):
  307. # Check that the executable argument works.
  308. #
  309. # On Unix (non-Mac and non-Windows), Python looks at args[0] to
  310. # determine where its standard library is, so we need the directory
  311. # of args[0] to be valid for the Popen() call to Python to succeed.
  312. # See also issue #16170 and issue #7774.
  313. doesnotexist = os.path.join(os.path.dirname(sys.executable),
  314. "doesnotexist")
  315. self._assert_python([doesnotexist, "-c"], executable=sys.executable)
  316. def test_bytes_executable(self):
  317. doesnotexist = os.path.join(os.path.dirname(sys.executable),
  318. "doesnotexist")
  319. self._assert_python([doesnotexist, "-c"],
  320. executable=os.fsencode(sys.executable))
  321. def test_pathlike_executable(self):
  322. doesnotexist = os.path.join(os.path.dirname(sys.executable),
  323. "doesnotexist")
  324. self._assert_python([doesnotexist, "-c"],
  325. executable=FakePath(sys.executable))
  326. def test_executable_takes_precedence(self):
  327. # Check that the executable argument takes precedence over args[0].
  328. #
  329. # Verify first that the call succeeds without the executable arg.
  330. pre_args = [sys.executable, "-c"]
  331. self._assert_python(pre_args)
  332. self.assertRaises(NONEXISTING_ERRORS,
  333. self._assert_python, pre_args,
  334. executable=NONEXISTING_CMD[0])
  335. @unittest.skipIf(mswindows, "executable argument replaces shell")
  336. def test_executable_replaces_shell(self):
  337. # Check that the executable argument replaces the default shell
  338. # when shell=True.
  339. self._assert_python([], executable=sys.executable, shell=True)
  340. @unittest.skipIf(mswindows, "executable argument replaces shell")
  341. def test_bytes_executable_replaces_shell(self):
  342. self._assert_python([], executable=os.fsencode(sys.executable),
  343. shell=True)
  344. @unittest.skipIf(mswindows, "executable argument replaces shell")
  345. def test_pathlike_executable_replaces_shell(self):
  346. self._assert_python([], executable=FakePath(sys.executable),
  347. shell=True)
  348. # For use in the test_cwd* tests below.
  349. def _normalize_cwd(self, cwd):
  350. # Normalize an expected cwd (for Tru64 support).
  351. # We can't use os.path.realpath since it doesn't expand Tru64 {memb}
  352. # strings. See bug #1063571.
  353. with os_helper.change_cwd(cwd):
  354. return os.getcwd()
  355. # For use in the test_cwd* tests below.
  356. def _split_python_path(self):
  357. # Return normalized (python_dir, python_base).
  358. python_path = os.path.realpath(sys.executable)
  359. return os.path.split(python_path)
  360. # For use in the test_cwd* tests below.
  361. def _assert_cwd(self, expected_cwd, python_arg, **kwargs):
  362. # Invoke Python via Popen, and assert that (1) the call succeeds,
  363. # and that (2) the current working directory of the child process
  364. # matches *expected_cwd*.
  365. p = subprocess.Popen([python_arg, "-c",
  366. "import os, sys; "
  367. "buf = sys.stdout.buffer; "
  368. "buf.write(os.getcwd().encode()); "
  369. "buf.flush(); "
  370. "sys.exit(47)"],
  371. stdout=subprocess.PIPE,
  372. **kwargs)
  373. self.addCleanup(p.stdout.close)
  374. p.wait()
  375. self.assertEqual(47, p.returncode)
  376. normcase = os.path.normcase
  377. self.assertEqual(normcase(expected_cwd),
  378. normcase(p.stdout.read().decode()))
  379. def test_cwd(self):
  380. # Check that cwd changes the cwd for the child process.
  381. temp_dir = tempfile.gettempdir()
  382. temp_dir = self._normalize_cwd(temp_dir)
  383. self._assert_cwd(temp_dir, sys.executable, cwd=temp_dir)
  384. def test_cwd_with_bytes(self):
  385. temp_dir = tempfile.gettempdir()
  386. temp_dir = self._normalize_cwd(temp_dir)
  387. self._assert_cwd(temp_dir, sys.executable, cwd=os.fsencode(temp_dir))
  388. def test_cwd_with_pathlike(self):
  389. temp_dir = tempfile.gettempdir()
  390. temp_dir = self._normalize_cwd(temp_dir)
  391. self._assert_cwd(temp_dir, sys.executable, cwd=FakePath(temp_dir))
  392. @unittest.skipIf(mswindows, "pending resolution of issue #15533")
  393. def test_cwd_with_relative_arg(self):
  394. # Check that Popen looks for args[0] relative to cwd if args[0]
  395. # is relative.
  396. python_dir, python_base = self._split_python_path()
  397. rel_python = os.path.join(os.curdir, python_base)
  398. with os_helper.temp_cwd() as wrong_dir:
  399. # Before calling with the correct cwd, confirm that the call fails
  400. # without cwd and with the wrong cwd.
  401. self.assertRaises(FileNotFoundError, subprocess.Popen,
  402. [rel_python])
  403. self.assertRaises(FileNotFoundError, subprocess.Popen,
  404. [rel_python], cwd=wrong_dir)
  405. python_dir = self._normalize_cwd(python_dir)
  406. self._assert_cwd(python_dir, rel_python, cwd=python_dir)
  407. @unittest.skipIf(mswindows, "pending resolution of issue #15533")
  408. def test_cwd_with_relative_executable(self):
  409. # Check that Popen looks for executable relative to cwd if executable
  410. # is relative (and that executable takes precedence over args[0]).
  411. python_dir, python_base = self._split_python_path()
  412. rel_python = os.path.join(os.curdir, python_base)
  413. doesntexist = "somethingyoudonthave"
  414. with os_helper.temp_cwd() as wrong_dir:
  415. # Before calling with the correct cwd, confirm that the call fails
  416. # without cwd and with the wrong cwd.
  417. self.assertRaises(FileNotFoundError, subprocess.Popen,
  418. [doesntexist], executable=rel_python)
  419. self.assertRaises(FileNotFoundError, subprocess.Popen,
  420. [doesntexist], executable=rel_python,
  421. cwd=wrong_dir)
  422. python_dir = self._normalize_cwd(python_dir)
  423. self._assert_cwd(python_dir, doesntexist, executable=rel_python,
  424. cwd=python_dir)
  425. def test_cwd_with_absolute_arg(self):
  426. # Check that Popen can find the executable when the cwd is wrong
  427. # if args[0] is an absolute path.
  428. python_dir, python_base = self._split_python_path()
  429. abs_python = os.path.join(python_dir, python_base)
  430. rel_python = os.path.join(os.curdir, python_base)
  431. with os_helper.temp_dir() as wrong_dir:
  432. # Before calling with an absolute path, confirm that using a
  433. # relative path fails.
  434. self.assertRaises(FileNotFoundError, subprocess.Popen,
  435. [rel_python], cwd=wrong_dir)
  436. wrong_dir = self._normalize_cwd(wrong_dir)
  437. self._assert_cwd(wrong_dir, abs_python, cwd=wrong_dir)
  438. @unittest.skipIf(sys.base_prefix != sys.prefix,
  439. 'Test is not venv-compatible')
  440. def test_executable_with_cwd(self):
  441. python_dir, python_base = self._split_python_path()
  442. python_dir = self._normalize_cwd(python_dir)
  443. self._assert_cwd(python_dir, "somethingyoudonthave",
  444. executable=sys.executable, cwd=python_dir)
  445. @unittest.skipIf(sys.base_prefix != sys.prefix,
  446. 'Test is not venv-compatible')
  447. @unittest.skipIf(sysconfig.is_python_build(),
  448. "need an installed Python. See #7774")
  449. def test_executable_without_cwd(self):
  450. # For a normal installation, it should work without 'cwd'
  451. # argument. For test runs in the build directory, see #7774.
  452. self._assert_cwd(os.getcwd(), "somethingyoudonthave",
  453. executable=sys.executable)
  454. def test_stdin_pipe(self):
  455. # stdin redirection
  456. p = subprocess.Popen([sys.executable, "-c",
  457. 'import sys; sys.exit(sys.stdin.read() == "pear")'],
  458. stdin=subprocess.PIPE)
  459. p.stdin.write(b"pear")
  460. p.stdin.close()
  461. p.wait()
  462. self.assertEqual(p.returncode, 1)
  463. def test_stdin_filedes(self):
  464. # stdin is set to open file descriptor
  465. tf = tempfile.TemporaryFile()
  466. self.addCleanup(tf.close)
  467. d = tf.fileno()
  468. os.write(d, b"pear")
  469. os.lseek(d, 0, 0)
  470. p = subprocess.Popen([sys.executable, "-c",
  471. 'import sys; sys.exit(sys.stdin.read() == "pear")'],
  472. stdin=d)
  473. p.wait()
  474. self.assertEqual(p.returncode, 1)
  475. def test_stdin_fileobj(self):
  476. # stdin is set to open file object
  477. tf = tempfile.TemporaryFile()
  478. self.addCleanup(tf.close)
  479. tf.write(b"pear")
  480. tf.seek(0)
  481. p = subprocess.Popen([sys.executable, "-c",
  482. 'import sys; sys.exit(sys.stdin.read() == "pear")'],
  483. stdin=tf)
  484. p.wait()
  485. self.assertEqual(p.returncode, 1)
  486. def test_stdout_pipe(self):
  487. # stdout redirection
  488. p = subprocess.Popen([sys.executable, "-c",
  489. 'import sys; sys.stdout.write("orange")'],
  490. stdout=subprocess.PIPE)
  491. with p:
  492. self.assertEqual(p.stdout.read(), b"orange")
  493. def test_stdout_filedes(self):
  494. # stdout is set to open file descriptor
  495. tf = tempfile.TemporaryFile()
  496. self.addCleanup(tf.close)
  497. d = tf.fileno()
  498. p = subprocess.Popen([sys.executable, "-c",
  499. 'import sys; sys.stdout.write("orange")'],
  500. stdout=d)
  501. p.wait()
  502. os.lseek(d, 0, 0)
  503. self.assertEqual(os.read(d, 1024), b"orange")
  504. def test_stdout_fileobj(self):
  505. # stdout is set to open file object
  506. tf = tempfile.TemporaryFile()
  507. self.addCleanup(tf.close)
  508. p = subprocess.Popen([sys.executable, "-c",
  509. 'import sys; sys.stdout.write("orange")'],
  510. stdout=tf)
  511. p.wait()
  512. tf.seek(0)
  513. self.assertEqual(tf.read(), b"orange")
  514. def test_stderr_pipe(self):
  515. # stderr redirection
  516. p = subprocess.Popen([sys.executable, "-c",
  517. 'import sys; sys.stderr.write("strawberry")'],
  518. stderr=subprocess.PIPE)
  519. with p:
  520. self.assertEqual(p.stderr.read(), b"strawberry")
  521. def test_stderr_filedes(self):
  522. # stderr is set to open file descriptor
  523. tf = tempfile.TemporaryFile()
  524. self.addCleanup(tf.close)
  525. d = tf.fileno()
  526. p = subprocess.Popen([sys.executable, "-c",
  527. 'import sys; sys.stderr.write("strawberry")'],
  528. stderr=d)
  529. p.wait()
  530. os.lseek(d, 0, 0)
  531. self.assertEqual(os.read(d, 1024), b"strawberry")
  532. def test_stderr_fileobj(self):
  533. # stderr is set to open file object
  534. tf = tempfile.TemporaryFile()
  535. self.addCleanup(tf.close)
  536. p = subprocess.Popen([sys.executable, "-c",
  537. 'import sys; sys.stderr.write("strawberry")'],
  538. stderr=tf)
  539. p.wait()
  540. tf.seek(0)
  541. self.assertEqual(tf.read(), b"strawberry")
  542. def test_stderr_redirect_with_no_stdout_redirect(self):
  543. # test stderr=STDOUT while stdout=None (not set)
  544. # - grandchild prints to stderr
  545. # - child redirects grandchild's stderr to its stdout
  546. # - the parent should get grandchild's stderr in child's stdout
  547. p = subprocess.Popen([sys.executable, "-c",
  548. 'import sys, subprocess;'
  549. 'rc = subprocess.call([sys.executable, "-c",'
  550. ' "import sys;"'
  551. ' "sys.stderr.write(\'42\')"],'
  552. ' stderr=subprocess.STDOUT);'
  553. 'sys.exit(rc)'],
  554. stdout=subprocess.PIPE,
  555. stderr=subprocess.PIPE)
  556. stdout, stderr = p.communicate()
  557. #NOTE: stdout should get stderr from grandchild
  558. self.assertEqual(stdout, b'42')
  559. self.assertEqual(stderr, b'') # should be empty
  560. self.assertEqual(p.returncode, 0)
  561. def test_stdout_stderr_pipe(self):
  562. # capture stdout and stderr to the same pipe
  563. p = subprocess.Popen([sys.executable, "-c",
  564. 'import sys;'
  565. 'sys.stdout.write("apple");'
  566. 'sys.stdout.flush();'
  567. 'sys.stderr.write("orange")'],
  568. stdout=subprocess.PIPE,
  569. stderr=subprocess.STDOUT)
  570. with p:
  571. self.assertEqual(p.stdout.read(), b"appleorange")
  572. def test_stdout_stderr_file(self):
  573. # capture stdout and stderr to the same open file
  574. tf = tempfile.TemporaryFile()
  575. self.addCleanup(tf.close)
  576. p = subprocess.Popen([sys.executable, "-c",
  577. 'import sys;'
  578. 'sys.stdout.write("apple");'
  579. 'sys.stdout.flush();'
  580. 'sys.stderr.write("orange")'],
  581. stdout=tf,
  582. stderr=tf)
  583. p.wait()
  584. tf.seek(0)
  585. self.assertEqual(tf.read(), b"appleorange")
  586. def test_stdout_filedes_of_stdout(self):
  587. # stdout is set to 1 (#1531862).
  588. # To avoid printing the text on stdout, we do something similar to
  589. # test_stdout_none (see above). The parent subprocess calls the child
  590. # subprocess passing stdout=1, and this test uses stdout=PIPE in
  591. # order to capture and check the output of the parent. See #11963.
  592. code = ('import sys, subprocess; '
  593. 'rc = subprocess.call([sys.executable, "-c", '
  594. ' "import os, sys; sys.exit(os.write(sys.stdout.fileno(), '
  595. 'b\'test with stdout=1\'))"], stdout=1); '
  596. 'assert rc == 18')
  597. p = subprocess.Popen([sys.executable, "-c", code],
  598. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  599. self.addCleanup(p.stdout.close)
  600. self.addCleanup(p.stderr.close)
  601. out, err = p.communicate()
  602. self.assertEqual(p.returncode, 0, err)
  603. self.assertEqual(out.rstrip(), b'test with stdout=1')
  604. def test_stdout_devnull(self):
  605. p = subprocess.Popen([sys.executable, "-c",
  606. 'for i in range(10240):'
  607. 'print("x" * 1024)'],
  608. stdout=subprocess.DEVNULL)
  609. p.wait()
  610. self.assertEqual(p.stdout, None)
  611. def test_stderr_devnull(self):
  612. p = subprocess.Popen([sys.executable, "-c",
  613. 'import sys\n'
  614. 'for i in range(10240):'
  615. 'sys.stderr.write("x" * 1024)'],
  616. stderr=subprocess.DEVNULL)
  617. p.wait()
  618. self.assertEqual(p.stderr, None)
  619. def test_stdin_devnull(self):
  620. p = subprocess.Popen([sys.executable, "-c",
  621. 'import sys;'
  622. 'sys.stdin.read(1)'],
  623. stdin=subprocess.DEVNULL)
  624. p.wait()
  625. self.assertEqual(p.stdin, None)
  626. @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
  627. 'fcntl.F_GETPIPE_SZ required for test.')
  628. def test_pipesizes(self):
  629. test_pipe_r, test_pipe_w = os.pipe()
  630. try:
  631. # Get the default pipesize with F_GETPIPE_SZ
  632. pipesize_default = fcntl.fcntl(test_pipe_w, fcntl.F_GETPIPE_SZ)
  633. finally:
  634. os.close(test_pipe_r)
  635. os.close(test_pipe_w)
  636. pipesize = pipesize_default // 2
  637. if pipesize < 512: # the POSIX minimum
  638. raise unittest.SkitTest(
  639. 'default pipesize too small to perform test.')
  640. p = subprocess.Popen(
  641. [sys.executable, "-c",
  642. 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
  643. 'sys.stderr.write("error!")'],
  644. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  645. stderr=subprocess.PIPE, pipesize=pipesize)
  646. try:
  647. for fifo in [p.stdin, p.stdout, p.stderr]:
  648. self.assertEqual(
  649. fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
  650. pipesize)
  651. # Windows pipe size can be acquired via GetNamedPipeInfoFunction
  652. # https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-getnamedpipeinfo
  653. # However, this function is not yet in _winapi.
  654. p.stdin.write(b"pear")
  655. p.stdin.close()
  656. p.stdout.close()
  657. p.stderr.close()
  658. finally:
  659. p.kill()
  660. p.wait()
  661. @unittest.skipUnless(fcntl and hasattr(fcntl, 'F_GETPIPE_SZ'),
  662. 'fcntl.F_GETPIPE_SZ required for test.')
  663. def test_pipesize_default(self):
  664. p = subprocess.Popen(
  665. [sys.executable, "-c",
  666. 'import sys; sys.stdin.read(); sys.stdout.write("out"); '
  667. 'sys.stderr.write("error!")'],
  668. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  669. stderr=subprocess.PIPE, pipesize=-1)
  670. try:
  671. fp_r, fp_w = os.pipe()
  672. try:
  673. default_pipesize = fcntl.fcntl(fp_w, fcntl.F_GETPIPE_SZ)
  674. for fifo in [p.stdin, p.stdout, p.stderr]:
  675. self.assertEqual(
  676. fcntl.fcntl(fifo.fileno(), fcntl.F_GETPIPE_SZ),
  677. default_pipesize)
  678. finally:
  679. os.close(fp_r)
  680. os.close(fp_w)
  681. # On other platforms we cannot test the pipe size (yet). But above
  682. # code using pipesize=-1 should not crash.
  683. p.stdin.close()
  684. p.stdout.close()
  685. p.stderr.close()
  686. finally:
  687. p.kill()
  688. p.wait()
  689. def test_env(self):
  690. newenv = os.environ.copy()
  691. newenv["FRUIT"] = "orange"
  692. with subprocess.Popen([sys.executable, "-c",
  693. 'import sys,os;'
  694. 'sys.stdout.write(os.getenv("FRUIT"))'],
  695. stdout=subprocess.PIPE,
  696. env=newenv) as p:
  697. stdout, stderr = p.communicate()
  698. self.assertEqual(stdout, b"orange")
  699. # Windows requires at least the SYSTEMROOT environment variable to start
  700. # Python
  701. @unittest.skipIf(sys.platform == 'win32',
  702. 'cannot test an empty env on Windows')
  703. @unittest.skipIf(sysconfig.get_config_var('Py_ENABLE_SHARED') == 1,
  704. 'The Python shared library cannot be loaded '
  705. 'with an empty environment.')
  706. def test_empty_env(self):
  707. """Verify that env={} is as empty as possible."""
  708. def is_env_var_to_ignore(n):
  709. """Determine if an environment variable is under our control."""
  710. # This excludes some __CF_* and VERSIONER_* keys MacOS insists
  711. # on adding even when the environment in exec is empty.
  712. # Gentoo sandboxes also force LD_PRELOAD and SANDBOX_* to exist.
  713. return ('VERSIONER' in n or '__CF' in n or # MacOS
  714. n == 'LD_PRELOAD' or n.startswith('SANDBOX') or # Gentoo
  715. n == 'LC_CTYPE') # Locale coercion triggered
  716. with subprocess.Popen([sys.executable, "-c",
  717. 'import os; print(list(os.environ.keys()))'],
  718. stdout=subprocess.PIPE, env={}) as p:
  719. stdout, stderr = p.communicate()
  720. child_env_names = eval(stdout.strip())
  721. self.assertIsInstance(child_env_names, list)
  722. child_env_names = [k for k in child_env_names
  723. if not is_env_var_to_ignore(k)]
  724. self.assertEqual(child_env_names, [])
  725. def test_invalid_cmd(self):
  726. # null character in the command name
  727. cmd = sys.executable + '\0'
  728. with self.assertRaises(ValueError):
  729. subprocess.Popen([cmd, "-c", "pass"])
  730. # null character in the command argument
  731. with self.assertRaises(ValueError):
  732. subprocess.Popen([sys.executable, "-c", "pass#\0"])
  733. def test_invalid_env(self):
  734. # null character in the environment variable name
  735. newenv = os.environ.copy()
  736. newenv["FRUIT\0VEGETABLE"] = "cabbage"
  737. with self.assertRaises(ValueError):
  738. subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
  739. # null character in the environment variable value
  740. newenv = os.environ.copy()
  741. newenv["FRUIT"] = "orange\0VEGETABLE=cabbage"
  742. with self.assertRaises(ValueError):
  743. subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
  744. # equal character in the environment variable name
  745. newenv = os.environ.copy()
  746. newenv["FRUIT=ORANGE"] = "lemon"
  747. with self.assertRaises(ValueError):
  748. subprocess.Popen(ZERO_RETURN_CMD, env=newenv)
  749. # equal character in the environment variable value
  750. newenv = os.environ.copy()
  751. newenv["FRUIT"] = "orange=lemon"
  752. with subprocess.Popen([sys.executable, "-c",
  753. 'import sys, os;'
  754. 'sys.stdout.write(os.getenv("FRUIT"))'],
  755. stdout=subprocess.PIPE,
  756. env=newenv) as p:
  757. stdout, stderr = p.communicate()
  758. self.assertEqual(stdout, b"orange=lemon")
  759. def test_communicate_stdin(self):
  760. p = subprocess.Popen([sys.executable, "-c",
  761. 'import sys;'
  762. 'sys.exit(sys.stdin.read() == "pear")'],
  763. stdin=subprocess.PIPE)
  764. p.communicate(b"pear")
  765. self.assertEqual(p.returncode, 1)
  766. def test_communicate_stdout(self):
  767. p = subprocess.Popen([sys.executable, "-c",
  768. 'import sys; sys.stdout.write("pineapple")'],
  769. stdout=subprocess.PIPE)
  770. (stdout, stderr) = p.communicate()
  771. self.assertEqual(stdout, b"pineapple")
  772. self.assertEqual(stderr, None)
  773. def test_communicate_stderr(self):
  774. p = subprocess.Popen([sys.executable, "-c",
  775. 'import sys; sys.stderr.write("pineapple")'],
  776. stderr=subprocess.PIPE)
  777. (stdout, stderr) = p.communicate()
  778. self.assertEqual(stdout, None)
  779. self.assertEqual(stderr, b"pineapple")
  780. def test_communicate(self):
  781. p = subprocess.Popen([sys.executable, "-c",
  782. 'import sys,os;'
  783. 'sys.stderr.write("pineapple");'
  784. 'sys.stdout.write(sys.stdin.read())'],
  785. stdin=subprocess.PIPE,
  786. stdout=subprocess.PIPE,
  787. stderr=subprocess.PIPE)
  788. self.addCleanup(p.stdout.close)
  789. self.addCleanup(p.stderr.close)
  790. self.addCleanup(p.stdin.close)
  791. (stdout, stderr) = p.communicate(b"banana")
  792. self.assertEqual(stdout, b"banana")
  793. self.assertEqual(stderr, b"pineapple")
  794. def test_communicate_timeout(self):
  795. p = subprocess.Popen([sys.executable, "-c",
  796. 'import sys,os,time;'
  797. 'sys.stderr.write("pineapple\\n");'
  798. 'time.sleep(1);'
  799. 'sys.stderr.write("pear\\n");'
  800. 'sys.stdout.write(sys.stdin.read())'],
  801. universal_newlines=True,
  802. stdin=subprocess.PIPE,
  803. stdout=subprocess.PIPE,
  804. stderr=subprocess.PIPE)
  805. self.assertRaises(subprocess.TimeoutExpired, p.communicate, "banana",
  806. timeout=0.3)
  807. # Make sure we can keep waiting for it, and that we get the whole output
  808. # after it completes.
  809. (stdout, stderr) = p.communicate()
  810. self.assertEqual(stdout, "banana")
  811. self.assertEqual(stderr.encode(), b"pineapple\npear\n")
  812. def test_communicate_timeout_large_output(self):
  813. # Test an expiring timeout while the child is outputting lots of data.
  814. p = subprocess.Popen([sys.executable, "-c",
  815. 'import sys,os,time;'
  816. 'sys.stdout.write("a" * (64 * 1024));'
  817. 'time.sleep(0.2);'
  818. 'sys.stdout.write("a" * (64 * 1024));'
  819. 'time.sleep(0.2);'
  820. 'sys.stdout.write("a" * (64 * 1024));'
  821. 'time.sleep(0.2);'
  822. 'sys.stdout.write("a" * (64 * 1024));'],
  823. stdout=subprocess.PIPE)
  824. self.assertRaises(subprocess.TimeoutExpired, p.communicate, timeout=0.4)
  825. (stdout, _) = p.communicate()
  826. self.assertEqual(len(stdout), 4 * 64 * 1024)
  827. # Test for the fd leak reported in http://bugs.python.org/issue2791.
  828. def test_communicate_pipe_fd_leak(self):
  829. for stdin_pipe in (False, True):
  830. for stdout_pipe in (False, True):
  831. for stderr_pipe in (False, True):
  832. options = {}
  833. if stdin_pipe:
  834. options['stdin'] = subprocess.PIPE
  835. if stdout_pipe:
  836. options['stdout'] = subprocess.PIPE
  837. if stderr_pipe:
  838. options['stderr'] = subprocess.PIPE
  839. if not options:
  840. continue
  841. p = subprocess.Popen(ZERO_RETURN_CMD, **options)
  842. p.communicate()
  843. if p.stdin is not None:
  844. self.assertTrue(p.stdin.closed)
  845. if p.stdout is not None:
  846. self.assertTrue(p.stdout.closed)
  847. if p.stderr is not None:
  848. self.assertTrue(p.stderr.closed)
  849. def test_communicate_returns(self):
  850. # communicate() should return None if no redirection is active
  851. p = subprocess.Popen([sys.executable, "-c",
  852. "import sys; sys.exit(47)"])
  853. (stdout, stderr) = p.communicate()
  854. self.assertEqual(stdout, None)
  855. self.assertEqual(stderr, None)
  856. def test_communicate_pipe_buf(self):
  857. # communicate() with writes larger than pipe_buf
  858. # This test will probably deadlock rather than fail, if
  859. # communicate() does not work properly.
  860. x, y = os.pipe()
  861. os.close(x)
  862. os.close(y)
  863. p = subprocess.Popen([sys.executable, "-c",
  864. 'import sys,os;'
  865. 'sys.stdout.write(sys.stdin.read(47));'
  866. 'sys.stderr.write("x" * %d);'
  867. 'sys.stdout.write(sys.stdin.read())' %
  868. support.PIPE_MAX_SIZE],
  869. stdin=subprocess.PIPE,
  870. stdout=subprocess.PIPE,
  871. stderr=subprocess.PIPE)
  872. self.addCleanup(p.stdout.close)
  873. self.addCleanup(p.stderr.close)
  874. self.addCleanup(p.stdin.close)
  875. string_to_write = b"a" * support.PIPE_MAX_SIZE
  876. (stdout, stderr) = p.communicate(string_to_write)
  877. self.assertEqual(stdout, string_to_write)
  878. def test_writes_before_communicate(self):
  879. # stdin.write before communicate()
  880. p = subprocess.Popen([sys.executable, "-c",
  881. 'import sys,os;'
  882. 'sys.stdout.write(sys.stdin.read())'],
  883. stdin=subprocess.PIPE,
  884. stdout=subprocess.PIPE,
  885. stderr=subprocess.PIPE)
  886. self.addCleanup(p.stdout.close)
  887. self.addCleanup(p.stderr.close)
  888. self.addCleanup(p.stdin.close)
  889. p.stdin.write(b"banana")
  890. (stdout, stderr) = p.communicate(b"split")
  891. self.assertEqual(stdout, b"bananasplit")
  892. self.assertEqual(stderr, b"")
  893. def test_universal_newlines_and_text(self):
  894. args = [
  895. sys.executable, "-c",
  896. 'import sys,os;' + SETBINARY +
  897. 'buf = sys.stdout.buffer;'
  898. 'buf.write(sys.stdin.readline().encode());'
  899. 'buf.flush();'
  900. 'buf.write(b"line2\\n");'
  901. 'buf.flush();'
  902. 'buf.write(sys.stdin.read().encode());'
  903. 'buf.flush();'
  904. 'buf.write(b"line4\\n");'
  905. 'buf.flush();'
  906. 'buf.write(b"line5\\r\\n");'
  907. 'buf.flush();'
  908. 'buf.write(b"line6\\r");'
  909. 'buf.flush();'
  910. 'buf.write(b"\\nline7");'
  911. 'buf.flush();'
  912. 'buf.write(b"\\nline8");']
  913. for extra_kwarg in ('universal_newlines', 'text'):
  914. p = subprocess.Popen(args, **{'stdin': subprocess.PIPE,
  915. 'stdout': subprocess.PIPE,
  916. extra_kwarg: True})
  917. with p:
  918. p.stdin.write("line1\n")
  919. p.stdin.flush()
  920. self.assertEqual(p.stdout.readline(), "line1\n")
  921. p.stdin.write("line3\n")
  922. p.stdin.close()
  923. self.addCleanup(p.stdout.close)
  924. self.assertEqual(p.stdout.readline(),
  925. "line2\n")
  926. self.assertEqual(p.stdout.read(6),
  927. "line3\n")
  928. self.assertEqual(p.stdout.read(),
  929. "line4\nline5\nline6\nline7\nline8")
  930. def test_universal_newlines_communicate(self):
  931. # universal newlines through communicate()
  932. p = subprocess.Popen([sys.executable, "-c",
  933. 'import sys,os;' + SETBINARY +
  934. 'buf = sys.stdout.buffer;'
  935. 'buf.write(b"line2\\n");'
  936. 'buf.flush();'
  937. 'buf.write(b"line4\\n");'
  938. 'buf.flush();'
  939. 'buf.write(b"line5\\r\\n");'
  940. 'buf.flush();'
  941. 'buf.write(b"line6\\r");'
  942. 'buf.flush();'
  943. 'buf.write(b"\\nline7");'
  944. 'buf.flush();'
  945. 'buf.write(b"\\nline8");'],
  946. stderr=subprocess.PIPE,
  947. stdout=subprocess.PIPE,
  948. universal_newlines=1)
  949. self.addCleanup(p.stdout.close)
  950. self.addCleanup(p.stderr.close)
  951. (stdout, stderr) = p.communicate()
  952. self.assertEqual(stdout,
  953. "line2\nline4\nline5\nline6\nline7\nline8")
  954. def test_universal_newlines_communicate_stdin(self):
  955. # universal newlines through communicate(), with only stdin
  956. p = subprocess.Popen([sys.executable, "-c",
  957. 'import sys,os;' + SETBINARY + textwrap.dedent('''
  958. s = sys.stdin.readline()
  959. assert s == "line1\\n", repr(s)
  960. s = sys.stdin.read()
  961. assert s == "line3\\n", repr(s)
  962. ''')],
  963. stdin=subprocess.PIPE,
  964. universal_newlines=1)
  965. (stdout, stderr) = p.communicate("line1\nline3\n")
  966. self.assertEqual(p.returncode, 0)
  967. def test_universal_newlines_communicate_input_none(self):
  968. # Test communicate(input=None) with universal newlines.
  969. #
  970. # We set stdout to PIPE because, as of this writing, a different
  971. # code path is tested when the number of pipes is zero or one.
  972. p = subprocess.Popen(ZERO_RETURN_CMD,
  973. stdin=subprocess.PIPE,
  974. stdout=subprocess.PIPE,
  975. universal_newlines=True)
  976. p.communicate()
  977. self.assertEqual(p.returncode, 0)
  978. def test_universal_newlines_communicate_stdin_stdout_stderr(self):
  979. # universal newlines through communicate(), with stdin, stdout, stderr
  980. p = subprocess.Popen([sys.executable, "-c",
  981. 'import sys,os;' + SETBINARY + textwrap.dedent('''
  982. s = sys.stdin.buffer.readline()
  983. sys.stdout.buffer.write(s)
  984. sys.stdout.buffer.write(b"line2\\r")
  985. sys.stderr.buffer.write(b"eline2\\n")
  986. s = sys.stdin.buffer.read()
  987. sys.stdout.buffer.write(s)
  988. sys.stdout.buffer.write(b"line4\\n")
  989. sys.stdout.buffer.write(b"line5\\r\\n")
  990. sys.stderr.buffer.write(b"eline6\\r")
  991. sys.stderr.buffer.write(b"eline7\\r\\nz")
  992. ''')],
  993. stdin=subprocess.PIPE,
  994. stderr=subprocess.PIPE,
  995. stdout=subprocess.PIPE,
  996. universal_newlines=True)
  997. self.addCleanup(p.stdout.close)
  998. self.addCleanup(p.stderr.close)
  999. (stdout, stderr) = p.communicate("line1\nline3\n")
  1000. self.assertEqual(p.returncode, 0)
  1001. self.assertEqual("line1\nline2\nline3\nline4\nline5\n", stdout)
  1002. # Python debug build push something like "[42442 refs]\n"
  1003. # to stderr at exit of subprocess.
  1004. self.assertTrue(stderr.startswith("eline2\neline6\neline7\n"))
  1005. def test_universal_newlines_communicate_encodings(self):
  1006. # Check that universal newlines mode works for various encodings,
  1007. # in particular for encodings in the UTF-16 and UTF-32 families.
  1008. # See issue #15595.
  1009. #
  1010. # UTF-16 and UTF-32-BE are sufficient to check both with BOM and
  1011. # without, and UTF-16 and UTF-32.
  1012. for encoding in ['utf-16', 'utf-32-be']:
  1013. code = ("import sys; "
  1014. r"sys.stdout.buffer.write('1\r\n2\r3\n4'.encode('%s'))" %
  1015. encoding)
  1016. args = [sys.executable, '-c', code]
  1017. # We set stdin to be non-None because, as of this writing,
  1018. # a different code path is used when the number of pipes is
  1019. # zero or one.
  1020. popen = subprocess.Popen(args,
  1021. stdin=subprocess.PIPE,
  1022. stdout=subprocess.PIPE,
  1023. encoding=encoding)
  1024. stdout, stderr = popen.communicate(input='')
  1025. self.assertEqual(stdout, '1\n2\n3\n4')
  1026. def test_communicate_errors(self):
  1027. for errors, expected in [
  1028. ('ignore', ''),
  1029. ('replace', '\ufffd\ufffd'),
  1030. ('surrogateescape', '\udc80\udc80'),
  1031. ('backslashreplace', '\\x80\\x80'),
  1032. ]:
  1033. code = ("import sys; "
  1034. r"sys.stdout.buffer.write(b'[\x80\x80]')")
  1035. args = [sys.executable, '-c', code]
  1036. # We set stdin to be non-None because, as of this writing,
  1037. # a different code path is used when the number of pipes is
  1038. # zero or one.
  1039. popen = subprocess.Popen(args,
  1040. stdin=subprocess.PIPE,
  1041. stdout=subprocess.PIPE,
  1042. encoding='utf-8',
  1043. errors=errors)
  1044. stdout, stderr = popen.communicate(input='')
  1045. self.assertEqual(stdout, '[{}]'.format(expected))
  1046. def test_no_leaking(self):
  1047. # Make sure we leak no resources
  1048. if not mswindows:
  1049. max_handles = 1026 # too much for most UNIX systems
  1050. else:
  1051. max_handles = 2050 # too much for (at least some) Windows setups
  1052. handles = []
  1053. tmpdir = tempfile.mkdtemp()
  1054. try:
  1055. for i in range(max_handles):
  1056. try:
  1057. tmpfile = os.path.join(tmpdir, os_helper.TESTFN)
  1058. handles.append(os.open(tmpfile, os.O_WRONLY|os.O_CREAT))
  1059. except OSError as e:
  1060. if e.errno != errno.EMFILE:
  1061. raise
  1062. break
  1063. else:
  1064. self.skipTest("failed to reach the file descriptor limit "
  1065. "(tried %d)" % max_handles)
  1066. # Close a couple of them (should be enough for a subprocess)
  1067. for i in range(10):
  1068. os.close(handles.pop())
  1069. # Loop creating some subprocesses. If one of them leaks some fds,
  1070. # the next loop iteration will fail by reaching the max fd limit.
  1071. for i in range(15):
  1072. p = subprocess.Popen([sys.executable, "-c",
  1073. "import sys;"
  1074. "sys.stdout.write(sys.stdin.read())"],
  1075. stdin=subprocess.PIPE,
  1076. stdout=subprocess.PIPE,
  1077. stderr=subprocess.PIPE)
  1078. data = p.communicate(b"lime")[0]
  1079. self.assertEqual(data, b"lime")
  1080. finally:
  1081. for h in handles:
  1082. os.close(h)
  1083. shutil.rmtree(tmpdir)
  1084. def test_list2cmdline(self):
  1085. self.assertEqual(subprocess.list2cmdline(['a b c', 'd', 'e']),
  1086. '"a b c" d e')
  1087. self.assertEqual(subprocess.list2cmdline(['ab"c', '\\', 'd']),
  1088. 'ab\\"c \\ d')
  1089. self.assertEqual(subprocess.list2cmdline(['ab"c', ' \\', 'd']),
  1090. 'ab\\"c " \\\\" d')
  1091. self.assertEqual(subprocess.list2cmdline(['a\\\\\\b', 'de fg', 'h']),
  1092. 'a\\\\\\b "de fg" h')
  1093. self.assertEqual(subprocess.list2cmdline(['a\\"b', 'c', 'd']),
  1094. 'a\\\\\\"b c d')
  1095. self.assertEqual(subprocess.list2cmdline(['a\\\\b c', 'd', 'e']),
  1096. '"a\\\\b c" d e')
  1097. self.assertEqual(subprocess.list2cmdline(['a\\\\b\\ c', 'd', 'e']),
  1098. '"a\\\\b\\ c" d e')
  1099. self.assertEqual(subprocess.list2cmdline(['ab', '']),
  1100. 'ab ""')
  1101. def test_poll(self):
  1102. p = subprocess.Popen([sys.executable, "-c",
  1103. "import os; os.read(0, 1)"],
  1104. stdin=subprocess.PIPE)
  1105. self.addCleanup(p.stdin.close)
  1106. self.assertIsNone(p.poll())
  1107. os.write(p.stdin.fileno(), b'A')
  1108. p.wait()
  1109. # Subsequent invocations should just return the returncode
  1110. self.assertEqual(p.poll(), 0)
  1111. def test_wait(self):
  1112. p = subprocess.Popen(ZERO_RETURN_CMD)
  1113. self.assertEqual(p.wait(), 0)
  1114. # Subsequent invocations should just return the returncode
  1115. self.assertEqual(p.wait(), 0)
  1116. def test_wait_timeout(self):
  1117. p = subprocess.Popen([sys.executable,
  1118. "-c", "import time; time.sleep(0.3)"])
  1119. with self.assertRaises(subprocess.TimeoutExpired) as c:
  1120. p.wait(timeout=0.0001)
  1121. self.assertIn("0.0001", str(c.exception)) # For coverage of __str__.
  1122. self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0)
  1123. def test_invalid_bufsize(self):
  1124. # an invalid type of the bufsize argument should raise
  1125. # TypeError.
  1126. with self.assertRaises(TypeError):
  1127. subprocess.Popen(ZERO_RETURN_CMD, "orange")
  1128. def test_bufsize_is_none(self):
  1129. # bufsize=None should be the same as bufsize=0.
  1130. p = subprocess.Popen(ZERO_RETURN_CMD, None)
  1131. self.assertEqual(p.wait(), 0)
  1132. # Again with keyword arg
  1133. p = subprocess.Popen(ZERO_RETURN_CMD, bufsize=None)
  1134. self.assertEqual(p.wait(), 0)
  1135. def _test_bufsize_equal_one(self, line, expected, universal_newlines):
  1136. # subprocess may deadlock with bufsize=1, see issue #21332
  1137. with subprocess.Popen([sys.executable, "-c", "import sys;"
  1138. "sys.stdout.write(sys.stdin.readline());"
  1139. "sys.stdout.flush()"],
  1140. stdin=subprocess.PIPE,
  1141. stdout=subprocess.PIPE,
  1142. stderr=subprocess.DEVNULL,
  1143. bufsize=1,
  1144. universal_newlines=universal_newlines) as p:
  1145. p.stdin.write(line) # expect that it flushes the line in text mode
  1146. os.close(p.stdin.fileno()) # close it without flushing the buffer
  1147. read_line = p.stdout.readline()
  1148. with support.SuppressCrashReport():
  1149. try:
  1150. p.stdin.close()
  1151. except OSError:
  1152. pass
  1153. p.stdin = None
  1154. self.assertEqual(p.returncode, 0)
  1155. self.assertEqual(read_line, expected)
  1156. def test_bufsize_equal_one_text_mode(self):
  1157. # line is flushed in text mode with bufsize=1.
  1158. # we should get the full line in return
  1159. line = "line\n"
  1160. self._test_bufsize_equal_one(line, line, universal_newlines=True)
  1161. def test_bufsize_equal_one_binary_mode(self):
  1162. # line is not flushed in binary mode with bufsize=1.
  1163. # we should get empty response
  1164. line = b'line' + os.linesep.encode() # assume ascii-based locale
  1165. with self.assertWarnsRegex(RuntimeWarning, 'line buffering'):
  1166. self._test_bufsize_equal_one(line, b'', universal_newlines=False)
  1167. def test_leaking_fds_on_error(self):
  1168. # see bug #5179: Popen leaks file descriptors to PIPEs if
  1169. # the child fails to execute; this will eventually exhaust
  1170. # the maximum number of open fds. 1024 seems a very common
  1171. # value for that limit, but Windows has 2048, so we loop
  1172. # 1024 times (each call leaked two fds).
  1173. for i in range(1024):
  1174. with self.assertRaises(NONEXISTING_ERRORS):
  1175. subprocess.Popen(NONEXISTING_CMD,
  1176. stdout=subprocess.PIPE,
  1177. stderr=subprocess.PIPE)
  1178. def test_nonexisting_with_pipes(self):
  1179. # bpo-30121: Popen with pipes must close properly pipes on error.
  1180. # Previously, os.close() was called with a Windows handle which is not
  1181. # a valid file descriptor.
  1182. #
  1183. # Run the test in a subprocess to control how the CRT reports errors
  1184. # and to get stderr content.
  1185. try:
  1186. import msvcrt
  1187. msvcrt.CrtSetReportMode
  1188. except (AttributeError, ImportError):
  1189. self.skipTest("need msvcrt.CrtSetReportMode")
  1190. code = textwrap.dedent(f"""
  1191. import msvcrt
  1192. import subprocess
  1193. cmd = {NONEXISTING_CMD!r}
  1194. for report_type in [msvcrt.CRT_WARN,
  1195. msvcrt.CRT_ERROR,
  1196. msvcrt.CRT_ASSERT]:
  1197. msvcrt.CrtSetReportMode(report_type, msvcrt.CRTDBG_MODE_FILE)
  1198. msvcrt.CrtSetReportFile(report_type, msvcrt.CRTDBG_FILE_STDERR)
  1199. try:
  1200. subprocess.Popen(cmd,
  1201. stdout=subprocess.PIPE,
  1202. stderr=subprocess.PIPE)
  1203. except OSError:
  1204. pass
  1205. """)
  1206. cmd = [sys.executable, "-c", code]
  1207. proc = subprocess.Popen(cmd,
  1208. stderr=subprocess.PIPE,
  1209. universal_newlines=True)
  1210. with proc:
  1211. stderr = proc.communicate()[1]
  1212. self.assertEqual(stderr, "")
  1213. self.assertEqual(proc.returncode, 0)
  1214. def test_double_close_on_error(self):
  1215. # Issue #18851
  1216. fds = []
  1217. def open_fds():
  1218. for i in range(20):
  1219. fds.extend(os.pipe())
  1220. time.sleep(0.001)
  1221. t = threading.Thread(target=open_fds)
  1222. t.start()
  1223. try:
  1224. with self.assertRaises(EnvironmentError):
  1225. subprocess.Popen(NONEXISTING_CMD,
  1226. stdin=subprocess.PIPE,
  1227. stdout=subprocess.PIPE,
  1228. stderr=subprocess.PIPE)
  1229. finally:
  1230. t.join()
  1231. exc = None
  1232. for fd in fds:
  1233. # If a double close occurred, some of those fds will
  1234. # already have been closed by mistake, and os.close()
  1235. # here will raise.
  1236. try:
  1237. os.close(fd)
  1238. except OSError as e:
  1239. exc = e
  1240. if exc is not None:
  1241. raise exc
  1242. def test_threadsafe_wait(self):
  1243. """Issue21291: Popen.wait() needs to be threadsafe for returncode."""
  1244. proc = subprocess.Popen([sys.executable, '-c',
  1245. 'import time; time.sleep(12)'])
  1246. self.assertEqual(proc.returncode, None)
  1247. results = []
  1248. def kill_proc_timer_thread():
  1249. results.append(('thread-start-poll-result', proc.poll()))
  1250. # terminate it from the thread and wait for the result.
  1251. proc.kill()
  1252. proc.wait()
  1253. results.append(('thread-after-kill-and-wait', proc.returncode))
  1254. # this wait should be a no-op given the above.
  1255. proc.wait()
  1256. results.append(('thread-after-second-wait', proc.returncode))
  1257. # This is a timing sensitive test, the failure mode is
  1258. # triggered when both the main thread and this thread are in
  1259. # the wait() call at once. The delay here is to allow the
  1260. # main thread to most likely be blocked in its wait() call.
  1261. t = threading.Timer(0.2, kill_proc_timer_thread)
  1262. t.start()
  1263. if mswindows:
  1264. expected_errorcode = 1
  1265. else:
  1266. # Should be -9 because of the proc.kill() from the thread.
  1267. expected_errorcode = -9
  1268. # Wait for the process to finish; the thread should kill it
  1269. # long before it finishes on its own. Supplying a timeout
  1270. # triggers a different code path for better coverage.
  1271. proc.wait(timeout=support.SHORT_TIMEOUT)
  1272. self.assertEqual(proc.returncode, expected_errorcode,
  1273. msg="unexpected result in wait from main thread")
  1274. # This should be a no-op with no change in returncode.
  1275. proc.wait()
  1276. self.assertEqual(proc.returncode, expected_errorcode,
  1277. msg="unexpected result in second main wait.")
  1278. t.join()
  1279. # Ensure that all of the thread results are as expected.
  1280. # When a race condition occurs in wait(), the returncode could
  1281. # be set by the wrong thread that doesn't actually have it
  1282. # leading to an incorrect value.
  1283. self.assertEqual([('thread-start-poll-result', None),
  1284. ('thread-after-kill-and-wait', expected_errorcode),
  1285. ('thread-after-second-wait', expected_errorcode)],
  1286. results)
  1287. def test_issue8780(self):
  1288. # Ensure that stdout is inherited from the parent
  1289. # if stdout=PIPE is not used
  1290. code = ';'.join((
  1291. 'import subprocess, sys',
  1292. 'retcode = subprocess.call('
  1293. "[sys.executable, '-c', 'print(\"Hello World!\")'])",
  1294. 'assert retcode == 0'))
  1295. output = subprocess.check_output([sys.executable, '-c', code])
  1296. self.assertTrue(output.startswith(b'Hello World!'), ascii(output))
  1297. def test_handles_closed_on_exception(self):
  1298. # If CreateProcess exits with an error, ensure the
  1299. # duplicate output handles are released
  1300. ifhandle, ifname = tempfile.mkstemp()
  1301. ofhandle, ofname = tempfile.mkstemp()
  1302. efhandle, efname = tempfile.mkstemp()
  1303. try:
  1304. subprocess.Popen (["*"], stdin=ifhandle, stdout=ofhandle,
  1305. stderr=efhandle)
  1306. except OSError:
  1307. os.close(ifhandle)
  1308. os.remove(ifname)
  1309. os.close(ofhandle)
  1310. os.remove(ofname)
  1311. os.close(efhandle)
  1312. os.remove(efname)
  1313. self.assertFalse(os.path.exists(ifname))
  1314. self.assertFalse(os.path.exists(ofname))
  1315. self.assertFalse(os.path.exists(efname))
  1316. def test_communicate_epipe(self):
  1317. # Issue 10963: communicate() should hide EPIPE
  1318. p = subprocess.Popen(ZERO_RETURN_CMD,
  1319. stdin=subprocess.PIPE,
  1320. stdout=subprocess.PIPE,
  1321. stderr=subprocess.PIPE)
  1322. self.addCleanup(p.stdout.close)
  1323. self.addCleanup(p.stderr.close)
  1324. self.addCleanup(p.stdin.close)
  1325. p.communicate(b"x" * 2**20)
  1326. def test_repr(self):
  1327. path_cmd = pathlib.Path("my-tool.py")
  1328. pathlib_cls = path_cmd.__class__.__name__
  1329. cases = [
  1330. ("ls", True, 123, "<Popen: returncode: 123 args: 'ls'>"),
  1331. ('a' * 100, True, 0,
  1332. "<Popen: returncode: 0 args: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...>"),
  1333. (["ls"], False, None, "<Popen: returncode: None args: ['ls']>"),
  1334. (["ls", '--my-opts', 'a' * 100], False, None,
  1335. "<Popen: returncode: None args: ['ls', '--my-opts', 'aaaaaaaaaaaaaaaaaaaaaaaa...>"),
  1336. (path_cmd, False, 7, f"<Popen: returncode: 7 args: {pathlib_cls}('my-tool.py')>")
  1337. ]
  1338. with unittest.mock.patch.object(subprocess.Popen, '_execute_child'):
  1339. for cmd, shell, code, sx in cases:
  1340. p = subprocess.Popen(cmd, shell=shell)
  1341. p.returncode = code
  1342. self.assertEqual(repr(p), sx)
  1343. def test_communicate_epipe_only_stdin(self):
  1344. # Issue 10963: communicate() should hide EPIPE
  1345. p = subprocess.Popen(ZERO_RETURN_CMD,
  1346. stdin=subprocess.PIPE)
  1347. self.addCleanup(p.stdin.close)
  1348. p.wait()
  1349. p.communicate(b"x" * 2**20)
  1350. @unittest.skipUnless(hasattr(signal, 'SIGUSR1'),
  1351. "Requires signal.SIGUSR1")
  1352. @unittest.skipUnless(hasattr(os, 'kill'),
  1353. "Requires os.kill")
  1354. @unittest.skipUnless(hasattr(os, 'getppid'),
  1355. "Requires os.getppid")
  1356. def test_communicate_eintr(self):
  1357. # Issue #12493: communicate() should handle EINTR
  1358. def handler(signum, frame):
  1359. pass
  1360. old_handler = signal.signal(signal.SIGUSR1, handler)
  1361. self.addCleanup(signal.signal, signal.SIGUSR1, old_handler)
  1362. args = [sys.executable, "-c",
  1363. 'import os, signal;'
  1364. 'os.kill(os.getppid(), signal.SIGUSR1)']
  1365. for stream in ('stdout', 'stderr'):
  1366. kw = {stream: subprocess.PIPE}
  1367. with subprocess.Popen(args, **kw) as process:
  1368. # communicate() will be interrupted by SIGUSR1
  1369. process.communicate()
  1370. # This test is Linux-ish specific for simplicity to at least have
  1371. # some coverage. It is not a platform specific bug.
  1372. @unittest.skipUnless(os.path.isdir('/proc/%d/fd' % os.getpid()),
  1373. "Linux specific")
  1374. def test_failed_child_execute_fd_leak(self):
  1375. """Test for the fork() failure fd leak reported in issue16327."""
  1376. fd_directory = '/proc/%d/fd' % os.getpid()
  1377. fds_before_popen = os.listdir(fd_directory)
  1378. with self.assertRaises(PopenTestException):
  1379. PopenExecuteChildRaises(
  1380. ZERO_RETURN_CMD, stdin=subprocess.PIPE,
  1381. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  1382. # NOTE: This test doesn't verify that the real _execute_child
  1383. # does not close the file descriptors itself on the way out
  1384. # during an exception. Code inspection has confirmed that.
  1385. fds_after_exception = os.listdir(fd_directory)
  1386. self.assertEqual(fds_before_popen, fds_after_exception)
  1387. @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
  1388. def test_file_not_found_includes_filename(self):
  1389. with self.assertRaises(FileNotFoundError) as c:
  1390. subprocess.call(['/opt/nonexistent_binary', 'with', 'some', 'args'])
  1391. self.assertEqual(c.exception.filename, '/opt/nonexistent_binary')
  1392. @unittest.skipIf(mswindows, "behavior currently not supported on Windows")
  1393. def test_file_not_found_with_bad_cwd(self):
  1394. with self.assertRaises(FileNotFoundError) as c:
  1395. subprocess.Popen(['exit', '0'], cwd='/some/nonexistent/directory')
  1396. self.assertEqual(c.exception.filename, '/some/nonexistent/directory')
  1397. def test_class_getitems(self):
  1398. self.assertIsInstance(subprocess.Popen[bytes], types.GenericAlias)
  1399. self.assertIsInstance(subprocess.CompletedProcess[str], types.GenericAlias)
  1400. @unittest.skipIf(not sysconfig.get_config_var("HAVE_VFORK"),
  1401. "vfork() not enabled by configure.")
  1402. @mock.patch("subprocess._fork_exec")
  1403. def test__use_vfork(self, mock_fork_exec):
  1404. self.assertTrue(subprocess._USE_VFORK) # The default value regardless.
  1405. mock_fork_exec.side_effect = RuntimeError("just testing args")
  1406. with self.assertRaises(RuntimeError):
  1407. subprocess.run([sys.executable, "-c", "pass"])
  1408. mock_fork_exec.assert_called_once()
  1409. self.assertTrue(mock_fork_exec.call_args.args[-1])
  1410. with mock.patch.object(subprocess, '_USE_VFORK', False):
  1411. with self.assertRaises(RuntimeError):
  1412. subprocess.run([sys.executable, "-c", "pass"])
  1413. self.assertFalse(mock_fork_exec.call_args_list[-1].args[-1])
  1414. class RunFuncTestCase(BaseTestCase):
  1415. def run_python(self, code, **kwargs):
  1416. """Run Python code in a subprocess using subprocess.run"""
  1417. argv = [sys.executable, "-c", code]
  1418. return subprocess.run(argv, **kwargs)
  1419. def test_returncode(self):
  1420. # call() function with sequence argument
  1421. cp = self.run_python("import sys; sys.exit(47)")
  1422. self.assertEqual(cp.returncode, 47)
  1423. with self.assertRaises(subprocess.CalledProcessError):
  1424. cp.check_returncode()
  1425. def test_check(self):
  1426. with self.assertRaises(subprocess.CalledProcessError) as c:
  1427. self.run_python("import sys; sys.exit(47)", check=True)
  1428. self.assertEqual(c.exception.returncode, 47)
  1429. def test_check_zero(self):
  1430. # check_returncode shouldn't raise when returncode is zero
  1431. cp = subprocess.run(ZERO_RETURN_CMD, check=True)
  1432. self.assertEqual(cp.returncode, 0)
  1433. def test_timeout(self):
  1434. # run() function with timeout argument; we want to test that the child
  1435. # process gets killed when the timeout expires. If the child isn't
  1436. # killed, this call will deadlock since subprocess.run waits for the
  1437. # child.
  1438. with self.assertRaises(subprocess.TimeoutExpired):
  1439. self.run_python("while True: pass", timeout=0.0001)
  1440. def test_capture_stdout(self):
  1441. # capture stdout with zero return code
  1442. cp = self.run_python("print('BDFL')", stdout=subprocess.PIPE)
  1443. self.assertIn(b'BDFL', cp.stdout)
  1444. def test_capture_stderr(self):
  1445. cp = self.run_python("import sys; sys.stderr.write('BDFL')",
  1446. stderr=subprocess.PIPE)
  1447. self.assertIn(b'BDFL', cp.stderr)
  1448. def test_check_output_stdin_arg(self):
  1449. # run() can be called with stdin set to a file
  1450. tf = tempfile.TemporaryFile()
  1451. self.addCleanup(tf.close)
  1452. tf.write(b'pear')
  1453. tf.seek(0)
  1454. cp = self.run_python(
  1455. "import sys; sys.stdout.write(sys.stdin.read().upper())",
  1456. stdin=tf, stdout=subprocess.PIPE)
  1457. self.assertIn(b'PEAR', cp.stdout)
  1458. def test_check_output_input_arg(self):
  1459. # check_output() can be called with input set to a string
  1460. cp = self.run_python(
  1461. "import sys; sys.stdout.write(sys.stdin.read().upper())",
  1462. input=b'pear', stdout=subprocess.PIPE)
  1463. self.assertIn(b'PEAR', cp.stdout)
  1464. def test_check_output_stdin_with_input_arg(self):
  1465. # run() refuses to accept 'stdin' with 'input'
  1466. tf = tempfile.TemporaryFile()
  1467. self.addCleanup(tf.close)
  1468. tf.write(b'pear')
  1469. tf.seek(0)
  1470. with self.assertRaises(ValueError,
  1471. msg="Expected ValueError when stdin and input args supplied.") as c:
  1472. output = self.run_python("print('will not be run')",
  1473. stdin=tf, input=b'hare')
  1474. self.assertIn('stdin', c.exception.args[0])
  1475. self.assertIn('input', c.exception.args[0])
  1476. def test_check_output_timeout(self):
  1477. with self.assertRaises(subprocess.TimeoutExpired) as c:
  1478. cp = self.run_python((
  1479. "import sys, time\n"
  1480. "sys.stdout.write('BDFL')\n"
  1481. "sys.stdout.flush()\n"
  1482. "time.sleep(3600)"),
  1483. # Some heavily loaded buildbots (sparc Debian 3.x) require
  1484. # this much time to start and print.
  1485. timeout=3, stdout=subprocess.PIPE)
  1486. self.assertEqual(c.exception.output, b'BDFL')
  1487. # output is aliased to stdout
  1488. self.assertEqual(c.exception.stdout, b'BDFL')
  1489. def test_run_kwargs(self):
  1490. newenv = os.environ.copy()
  1491. newenv["FRUIT"] = "banana"
  1492. cp = self.run_python(('import sys, os;'
  1493. 'sys.exit(33 if os.getenv("FRUIT")=="banana" else 31)'),
  1494. env=newenv)
  1495. self.assertEqual(cp.returncode, 33)
  1496. def test_run_with_pathlike_path(self):
  1497. # bpo-31961: test run(pathlike_object)
  1498. # the name of a command that can be run without
  1499. # any arguments that exit fast
  1500. prog = 'tree.com' if mswindows else 'ls'
  1501. path = shutil.which(prog)
  1502. if path is None:
  1503. self.skipTest(f'{prog} required for this test')
  1504. path = FakePath(path)
  1505. res = subprocess.run(path, stdout=subprocess.DEVNULL)
  1506. self.assertEqual(res.returncode, 0)
  1507. with self.assertRaises(TypeError):
  1508. subprocess.run(path, stdout=subprocess.DEVNULL, shell=True)
  1509. def test_run_with_bytes_path_and_arguments(self):
  1510. # bpo-31961: test run([bytes_object, b'additional arguments'])
  1511. path = os.fsencode(sys.executable)
  1512. args = [path, '-c', b'import sys; sys.exit(57)']
  1513. res = subprocess.run(args)
  1514. self.assertEqual(res.returncode, 57)
  1515. def test_run_with_pathlike_path_and_arguments(self):
  1516. # bpo-31961: test run([pathlike_object, 'additional arguments'])
  1517. path = FakePath(sys.executable)
  1518. args = [path, '-c', 'import sys; sys.exit(57)']
  1519. res = subprocess.run(args)
  1520. self.assertEqual(res.returncode, 57)
  1521. def test_capture_output(self):
  1522. cp = self.run_python(("import sys;"
  1523. "sys.stdout.write('BDFL'); "
  1524. "sys.stderr.write('FLUFL')"),
  1525. capture_output=True)
  1526. self.assertIn(b'BDFL', cp.stdout)
  1527. self.assertIn(b'FLUFL', cp.stderr)
  1528. def test_stdout_with_capture_output_arg(self):
  1529. # run() refuses to accept 'stdout' with 'capture_output'
  1530. tf = tempfile.TemporaryFile()
  1531. self.addCleanup(tf.close)
  1532. with self.assertRaises(ValueError,
  1533. msg=("Expected ValueError when stdout and capture_output "
  1534. "args supplied.")) as c:
  1535. output = self.run_python("print('will not be run')",
  1536. capture_output=True, stdout=tf)
  1537. self.assertIn('stdout', c.exception.args[0])
  1538. self.assertIn('capture_output', c.exception.args[0])
  1539. def test_stderr_with_capture_output_arg(self):
  1540. # run() refuses to accept 'stderr' with 'capture_output'
  1541. tf = tempfile.TemporaryFile()
  1542. self.addCleanup(tf.close)
  1543. with self.assertRaises(ValueError,
  1544. msg=("Expected ValueError when stderr and capture_output "
  1545. "args supplied.")) as c:
  1546. output = self.run_python("print('will not be run')",
  1547. capture_output=True, stderr=tf)
  1548. self.assertIn('stderr', c.exception.args[0])
  1549. self.assertIn('capture_output', c.exception.args[0])
  1550. # This test _might_ wind up a bit fragile on loaded build+test machines
  1551. # as it depends on the timing with wide enough margins for normal situations
  1552. # but does assert that it happened "soon enough" to believe the right thing
  1553. # happened.
  1554. @unittest.skipIf(mswindows, "requires posix like 'sleep' shell command")
  1555. def test_run_with_shell_timeout_and_capture_output(self):
  1556. """Output capturing after a timeout mustn't hang forever on open filehandles."""
  1557. before_secs = time.monotonic()
  1558. try:
  1559. subprocess.run('sleep 3', shell=True, timeout=0.1,
  1560. capture_output=True) # New session unspecified.
  1561. except subprocess.TimeoutExpired as exc:
  1562. after_secs = time.monotonic()
  1563. stacks = traceback.format_exc() # assertRaises doesn't give this.
  1564. else:
  1565. self.fail("TimeoutExpired not raised.")
  1566. self.assertLess(after_secs - before_secs, 1.5,
  1567. msg="TimeoutExpired was delayed! Bad traceback:\n```\n"
  1568. f"{stacks}```")
  1569. def test_encoding_warning(self):
  1570. code = textwrap.dedent("""\
  1571. from subprocess import *
  1572. run("echo hello", shell=True, text=True)
  1573. check_output("echo hello", shell=True, text=True)
  1574. """)
  1575. cp = subprocess.run([sys.executable, "-Xwarn_default_encoding", "-c", code],
  1576. capture_output=True)
  1577. lines = cp.stderr.splitlines()
  1578. self.assertEqual(len(lines), 2, lines)
  1579. self.assertTrue(lines[0].startswith(b"<string>:2: EncodingWarning: "))
  1580. self.assertTrue(lines[1].startswith(b"<string>:3: EncodingWarning: "))
  1581. def _get_test_grp_name():
  1582. for name_group in ('staff', 'nogroup', 'grp', 'nobody', 'nfsnobody'):
  1583. if grp:
  1584. try:
  1585. grp.getgrnam(name_group)
  1586. except KeyError:
  1587. continue
  1588. return name_group
  1589. else:
  1590. raise unittest.SkipTest('No identified group name to use for this test on this platform.')
  1591. @unittest.skipIf(mswindows, "POSIX specific tests")
  1592. class POSIXProcessTestCase(BaseTestCase):
  1593. def setUp(self):
  1594. super().setUp()
  1595. self._nonexistent_dir = "/_this/pa.th/does/not/exist"
  1596. def _get_chdir_exception(self):
  1597. try:
  1598. os.chdir(self._nonexistent_dir)
  1599. except OSError as e:
  1600. # This avoids hard coding the errno value or the OS perror()
  1601. # string and instead capture the exception that we want to see
  1602. # below for comparison.
  1603. desired_exception = e
  1604. else:
  1605. self.fail("chdir to nonexistent directory %s succeeded." %
  1606. self._nonexistent_dir)
  1607. return desired_exception
  1608. def test_exception_cwd(self):
  1609. """Test error in the child raised in the parent for a bad cwd."""
  1610. desired_exception = self._get_chdir_exception()
  1611. try:
  1612. p = subprocess.Popen([sys.executable, "-c", ""],
  1613. cwd=self._nonexistent_dir)
  1614. except OSError as e:
  1615. # Test that the child process chdir failure actually makes
  1616. # it up to the parent process as the correct exception.
  1617. self.assertEqual(desired_exception.errno, e.errno)
  1618. self.assertEqual(desired_exception.strerror, e.strerror)
  1619. self.assertEqual(desired_exception.filename, e.filename)
  1620. else:
  1621. self.fail("Expected OSError: %s" % desired_exception)
  1622. def test_exception_bad_executable(self):
  1623. """Test error in the child raised in the parent for a bad executable."""
  1624. desired_exception = self._get_chdir_exception()
  1625. try:
  1626. p = subprocess.Popen([sys.executable, "-c", ""],
  1627. executable=self._nonexistent_dir)
  1628. except OSError as e:
  1629. # Test that the child process exec failure actually makes
  1630. # it up to the parent process as the correct exception.
  1631. self.assertEqual(desired_exception.errno, e.errno)
  1632. self.assertEqual(desired_exception.strerror, e.strerror)
  1633. self.assertEqual(desired_exception.filename, e.filename)
  1634. else:
  1635. self.fail("Expected OSError: %s" % desired_exception)
  1636. def test_exception_bad_args_0(self):
  1637. """Test error in the child raised in the parent for a bad args[0]."""
  1638. desired_exception = self._get_chdir_exception()
  1639. try:
  1640. p = subprocess.Popen([self._nonexistent_dir, "-c", ""])
  1641. except OSError as e:
  1642. # Test that the child process exec failure actually makes
  1643. # it up to the parent process as the correct exception.
  1644. self.assertEqual(desired_exception.errno, e.errno)
  1645. self.assertEqual(desired_exception.strerror, e.strerror)
  1646. self.assertEqual(desired_exception.filename, e.filename)
  1647. else:
  1648. self.fail("Expected OSError: %s" % desired_exception)
  1649. # We mock the __del__ method for Popen in the next two tests
  1650. # because it does cleanup based on the pid returned by fork_exec
  1651. # along with issuing a resource warning if it still exists. Since
  1652. # we don't actually spawn a process in these tests we can forego
  1653. # the destructor. An alternative would be to set _child_created to
  1654. # False before the destructor is called but there is no easy way
  1655. # to do that
  1656. class PopenNoDestructor(subprocess.Popen):
  1657. def __del__(self):
  1658. pass
  1659. @mock.patch("subprocess._fork_exec")
  1660. def test_exception_errpipe_normal(self, fork_exec):
  1661. """Test error passing done through errpipe_write in the good case"""
  1662. def proper_error(*args):
  1663. errpipe_write = args[13]
  1664. # Write the hex for the error code EISDIR: 'is a directory'
  1665. err_code = '{:x}'.format(errno.EISDIR).encode()
  1666. os.write(errpipe_write, b"OSError:" + err_code + b":")
  1667. return 0
  1668. fork_exec.side_effect = proper_error
  1669. with mock.patch("subprocess.os.waitpid",
  1670. side_effect=ChildProcessError):
  1671. with self.assertRaises(IsADirectoryError):
  1672. self.PopenNoDestructor(["non_existent_command"])
  1673. @mock.patch("subprocess._fork_exec")
  1674. def test_exception_errpipe_bad_data(self, fork_exec):
  1675. """Test error passing done through errpipe_write where its not
  1676. in the expected format"""
  1677. error_data = b"\xFF\x00\xDE\xAD"
  1678. def bad_error(*args):
  1679. errpipe_write = args[13]
  1680. # Anything can be in the pipe, no assumptions should
  1681. # be made about its encoding, so we'll write some
  1682. # arbitrary hex bytes to test it out
  1683. os.write(errpipe_write, error_data)
  1684. return 0
  1685. fork_exec.side_effect = bad_error
  1686. with mock.patch("subprocess.os.waitpid",
  1687. side_effect=ChildProcessError):
  1688. with self.assertRaises(subprocess.SubprocessError) as e:
  1689. self.PopenNoDestructor(["non_existent_command"])
  1690. self.assertIn(repr(error_data), str(e.exception))
  1691. @unittest.skipIf(not os.path.exists('/proc/self/status'),
  1692. "need /proc/self/status")
  1693. def test_restore_signals(self):
  1694. # Blindly assume that cat exists on systems with /proc/self/status...
  1695. default_proc_status = subprocess.check_output(
  1696. ['cat', '/proc/self/status'],
  1697. restore_signals=False)
  1698. for line in default_proc_status.splitlines():
  1699. if line.startswith(b'SigIgn'):
  1700. default_sig_ign_mask = line
  1701. break
  1702. else:
  1703. self.skipTest("SigIgn not found in /proc/self/status.")
  1704. restored_proc_status = subprocess.check_output(
  1705. ['cat', '/proc/self/status'],
  1706. restore_signals=True)
  1707. for line in restored_proc_status.splitlines():
  1708. if line.startswith(b'SigIgn'):
  1709. restored_sig_ign_mask = line
  1710. break
  1711. self.assertNotEqual(default_sig_ign_mask, restored_sig_ign_mask,
  1712. msg="restore_signals=True should've unblocked "
  1713. "SIGPIPE and friends.")
  1714. def test_start_new_session(self):
  1715. # For code coverage of calling setsid(). We don't care if we get an
  1716. # EPERM error from it depending on the test execution environment, that
  1717. # still indicates that it was called.
  1718. try:
  1719. output = subprocess.check_output(
  1720. [sys.executable, "-c", "import os; print(os.getsid(0))"],
  1721. start_new_session=True)
  1722. except PermissionError as e:
  1723. if e.errno != errno.EPERM:
  1724. raise # EACCES?
  1725. else:
  1726. parent_sid = os.getsid(0)
  1727. child_sid = int(output)
  1728. self.assertNotEqual(parent_sid, child_sid)
  1729. @unittest.skipUnless(hasattr(os, 'setpgid') and hasattr(os, 'getpgid'),
  1730. 'no setpgid or getpgid on platform')
  1731. def test_process_group_0(self):
  1732. # For code coverage of calling setpgid(). We don't care if we get an
  1733. # EPERM error from it depending on the test execution environment, that
  1734. # still indicates that it was called.
  1735. try:
  1736. output = subprocess.check_output(
  1737. [sys.executable, "-c", "import os; print(os.getpgid(0))"],
  1738. process_group=0)
  1739. except PermissionError as e:
  1740. if e.errno != errno.EPERM:
  1741. raise # EACCES?
  1742. else:
  1743. parent_pgid = os.getpgid(0)
  1744. child_pgid = int(output)
  1745. self.assertNotEqual(parent_pgid, child_pgid)
  1746. @unittest.skipUnless(hasattr(os, 'setreuid'), 'no setreuid on platform')
  1747. def test_user(self):
  1748. # For code coverage of the user parameter. We don't care if we get an
  1749. # EPERM error from it depending on the test execution environment, that
  1750. # still indicates that it was called.
  1751. uid = os.geteuid()
  1752. test_users = [65534 if uid != 65534 else 65533, uid]
  1753. name_uid = "nobody" if sys.platform != 'darwin' else "unknown"
  1754. if pwd is not None:
  1755. try:
  1756. pwd.getpwnam(name_uid)
  1757. test_users.append(name_uid)
  1758. except KeyError:
  1759. # unknown user name
  1760. name_uid = None
  1761. for user in test_users:
  1762. # posix_spawn() may be used with close_fds=False
  1763. for close_fds in (False, True):
  1764. with self.subTest(user=user, close_fds=close_fds):
  1765. try:
  1766. output = subprocess.check_output(
  1767. [sys.executable, "-c",
  1768. "import os; print(os.getuid())"],
  1769. user=user,
  1770. close_fds=close_fds)
  1771. except PermissionError: # (EACCES, EPERM)
  1772. pass
  1773. except OSError as e:
  1774. if e.errno not in (errno.EACCES, errno.EPERM):
  1775. raise
  1776. else:
  1777. if isinstance(user, str):
  1778. user_uid = pwd.getpwnam(user).pw_uid
  1779. else:
  1780. user_uid = user
  1781. child_user = int(output)
  1782. self.assertEqual(child_user, user_uid)
  1783. with self.assertRaises(ValueError):
  1784. subprocess.check_call(ZERO_RETURN_CMD, user=-1)
  1785. with self.assertRaises(OverflowError):
  1786. subprocess.check_call(ZERO_RETURN_CMD,
  1787. cwd=os.curdir, env=os.environ, user=2**64)
  1788. if pwd is None and name_uid is not None:
  1789. with self.assertRaises(ValueError):
  1790. subprocess.check_call(ZERO_RETURN_CMD, user=name_uid)
  1791. @unittest.skipIf(hasattr(os, 'setreuid'), 'setreuid() available on platform')
  1792. def test_user_error(self):
  1793. with self.assertRaises(ValueError):
  1794. subprocess.check_call(ZERO_RETURN_CMD, user=65535)
  1795. @unittest.skipUnless(hasattr(os, 'setregid'), 'no setregid() on platform')
  1796. def test_group(self):
  1797. gid = os.getegid()
  1798. group_list = [65534 if gid != 65534 else 65533]
  1799. name_group = _get_test_grp_name()
  1800. if grp is not None:
  1801. group_list.append(name_group)
  1802. for group in group_list + [gid]:
  1803. # posix_spawn() may be used with close_fds=False
  1804. for close_fds in (False, True):
  1805. with self.subTest(group=group, close_fds=close_fds):
  1806. try:
  1807. output = subprocess.check_output(
  1808. [sys.executable, "-c",
  1809. "import os; print(os.getgid())"],
  1810. group=group,
  1811. close_fds=close_fds)
  1812. except PermissionError: # (EACCES, EPERM)
  1813. pass
  1814. else:
  1815. if isinstance(group, str):
  1816. group_gid = grp.getgrnam(group).gr_gid
  1817. else:
  1818. group_gid = group
  1819. child_group = int(output)
  1820. self.assertEqual(child_group, group_gid)
  1821. # make sure we bomb on negative values
  1822. with self.assertRaises(ValueError):
  1823. subprocess.check_call(ZERO_RETURN_CMD, group=-1)
  1824. with self.assertRaises(OverflowError):
  1825. subprocess.check_call(ZERO_RETURN_CMD,
  1826. cwd=os.curdir, env=os.environ, group=2**64)
  1827. if grp is None:
  1828. with self.assertRaises(ValueError):
  1829. subprocess.check_call(ZERO_RETURN_CMD, group=name_group)
  1830. @unittest.skipIf(hasattr(os, 'setregid'), 'setregid() available on platform')
  1831. def test_group_error(self):
  1832. with self.assertRaises(ValueError):
  1833. subprocess.check_call(ZERO_RETURN_CMD, group=65535)
  1834. @unittest.skipUnless(hasattr(os, 'setgroups'), 'no setgroups() on platform')
  1835. def test_extra_groups(self):
  1836. gid = os.getegid()
  1837. group_list = [65534 if gid != 65534 else 65533]
  1838. name_group = _get_test_grp_name()
  1839. perm_error = False
  1840. if grp is not None:
  1841. group_list.append(name_group)
  1842. try:
  1843. output = subprocess.check_output(
  1844. [sys.executable, "-c",
  1845. "import os, sys, json; json.dump(os.getgroups(), sys.stdout)"],
  1846. extra_groups=group_list)
  1847. except OSError as ex:
  1848. if ex.errno != errno.EPERM:
  1849. raise
  1850. perm_error = True
  1851. else:
  1852. parent_groups = os.getgroups()
  1853. child_groups = json.loads(output)
  1854. if grp is not None:
  1855. desired_gids = [grp.getgrnam(g).gr_gid if isinstance(g, str) else g
  1856. for g in group_list]
  1857. else:
  1858. desired_gids = group_list
  1859. if perm_error:
  1860. self.assertEqual(set(child_groups), set(parent_groups))
  1861. else:
  1862. self.assertEqual(set(desired_gids), set(child_groups))
  1863. # make sure we bomb on negative values
  1864. with self.assertRaises(ValueError):
  1865. subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[-1])
  1866. with self.assertRaises(ValueError):
  1867. subprocess.check_call(ZERO_RETURN_CMD,
  1868. cwd=os.curdir, env=os.environ,
  1869. extra_groups=[2**64])
  1870. if grp is None:
  1871. with self.assertRaises(ValueError):
  1872. subprocess.check_call(ZERO_RETURN_CMD,
  1873. extra_groups=[name_group])
  1874. @unittest.skipIf(hasattr(os, 'setgroups'), 'setgroups() available on platform')
  1875. def test_extra_groups_error(self):
  1876. with self.assertRaises(ValueError):
  1877. subprocess.check_call(ZERO_RETURN_CMD, extra_groups=[])
  1878. @unittest.skipIf(mswindows or not hasattr(os, 'umask'),
  1879. 'POSIX umask() is not available.')
  1880. def test_umask(self):
  1881. tmpdir = None
  1882. try:
  1883. tmpdir = tempfile.mkdtemp()
  1884. name = os.path.join(tmpdir, "beans")
  1885. # We set an unusual umask in the child so as a unique mode
  1886. # for us to test the child's touched file for.
  1887. subprocess.check_call(
  1888. [sys.executable, "-c", f"open({name!r}, 'w').close()"],
  1889. umask=0o053)
  1890. # Ignore execute permissions entirely in our test,
  1891. # filesystems could be mounted to ignore or force that.
  1892. st_mode = os.stat(name).st_mode & 0o666
  1893. expected_mode = 0o624
  1894. self.assertEqual(expected_mode, st_mode,
  1895. msg=f'{oct(expected_mode)} != {oct(st_mode)}')
  1896. finally:
  1897. if tmpdir is not None:
  1898. shutil.rmtree(tmpdir)
  1899. def test_run_abort(self):
  1900. # returncode handles signal termination
  1901. with support.SuppressCrashReport():
  1902. p = subprocess.Popen([sys.executable, "-c",
  1903. 'import os; os.abort()'])
  1904. p.wait()
  1905. self.assertEqual(-p.returncode, signal.SIGABRT)
  1906. def test_CalledProcessError_str_signal(self):
  1907. err = subprocess.CalledProcessError(-int(signal.SIGABRT), "fake cmd")
  1908. error_string = str(err)
  1909. # We're relying on the repr() of the signal.Signals intenum to provide
  1910. # the word signal, the signal name and the numeric value.
  1911. self.assertIn("signal", error_string.lower())
  1912. # We're not being specific about the signal name as some signals have
  1913. # multiple names and which name is revealed can vary.
  1914. self.assertIn("SIG", error_string)
  1915. self.assertIn(str(signal.SIGABRT), error_string)
  1916. def test_CalledProcessError_str_unknown_signal(self):
  1917. err = subprocess.CalledProcessError(-9876543, "fake cmd")
  1918. error_string = str(err)
  1919. self.assertIn("unknown signal 9876543.", error_string)
  1920. def test_CalledProcessError_str_non_zero(self):
  1921. err = subprocess.CalledProcessError(2, "fake cmd")
  1922. error_string = str(err)
  1923. self.assertIn("non-zero exit status 2.", error_string)
  1924. def test_preexec(self):
  1925. # DISCLAIMER: Setting environment variables is *not* a good use
  1926. # of a preexec_fn. This is merely a test.
  1927. p = subprocess.Popen([sys.executable, "-c",
  1928. 'import sys,os;'
  1929. 'sys.stdout.write(os.getenv("FRUIT"))'],
  1930. stdout=subprocess.PIPE,
  1931. preexec_fn=lambda: os.putenv("FRUIT", "apple"))
  1932. with p:
  1933. self.assertEqual(p.stdout.read(), b"apple")
  1934. def test_preexec_exception(self):
  1935. def raise_it():
  1936. raise ValueError("What if two swallows carried a coconut?")
  1937. try:
  1938. p = subprocess.Popen([sys.executable, "-c", ""],
  1939. preexec_fn=raise_it)
  1940. except subprocess.SubprocessError as e:
  1941. self.assertTrue(
  1942. subprocess._fork_exec,
  1943. "Expected a ValueError from the preexec_fn")
  1944. except ValueError as e:
  1945. self.assertIn("coconut", e.args[0])
  1946. else:
  1947. self.fail("Exception raised by preexec_fn did not make it "
  1948. "to the parent process.")
  1949. class _TestExecuteChildPopen(subprocess.Popen):
  1950. """Used to test behavior at the end of _execute_child."""
  1951. def __init__(self, testcase, *args, **kwargs):
  1952. self._testcase = testcase
  1953. subprocess.Popen.__init__(self, *args, **kwargs)
  1954. def _execute_child(self, *args, **kwargs):
  1955. try:
  1956. subprocess.Popen._execute_child(self, *args, **kwargs)
  1957. finally:
  1958. # Open a bunch of file descriptors and verify that
  1959. # none of them are the same as the ones the Popen
  1960. # instance is using for stdin/stdout/stderr.
  1961. devzero_fds = [os.open("/dev/zero", os.O_RDONLY)
  1962. for _ in range(8)]
  1963. try:
  1964. for fd in devzero_fds:
  1965. self._testcase.assertNotIn(
  1966. fd, (self.stdin.fileno(), self.stdout.fileno(),
  1967. self.stderr.fileno()),
  1968. msg="At least one fd was closed early.")
  1969. finally:
  1970. for fd in devzero_fds:
  1971. os.close(fd)
  1972. @unittest.skipIf(not os.path.exists("/dev/zero"), "/dev/zero required.")
  1973. def test_preexec_errpipe_does_not_double_close_pipes(self):
  1974. """Issue16140: Don't double close pipes on preexec error."""
  1975. def raise_it():
  1976. raise subprocess.SubprocessError(
  1977. "force the _execute_child() errpipe_data path.")
  1978. with self.assertRaises(subprocess.SubprocessError):
  1979. self._TestExecuteChildPopen(
  1980. self, ZERO_RETURN_CMD,
  1981. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1982. stderr=subprocess.PIPE, preexec_fn=raise_it)
  1983. def test_preexec_gc_module_failure(self):
  1984. # This tests the code that disables garbage collection if the child
  1985. # process will execute any Python.
  1986. enabled = gc.isenabled()
  1987. try:
  1988. gc.disable()
  1989. self.assertFalse(gc.isenabled())
  1990. subprocess.call([sys.executable, '-c', ''],
  1991. preexec_fn=lambda: None)
  1992. self.assertFalse(gc.isenabled(),
  1993. "Popen enabled gc when it shouldn't.")
  1994. gc.enable()
  1995. self.assertTrue(gc.isenabled())
  1996. subprocess.call([sys.executable, '-c', ''],
  1997. preexec_fn=lambda: None)
  1998. self.assertTrue(gc.isenabled(), "Popen left gc disabled.")
  1999. finally:
  2000. if not enabled:
  2001. gc.disable()
  2002. @unittest.skipIf(
  2003. sys.platform == 'darwin', 'setrlimit() seems to fail on OS X')
  2004. def test_preexec_fork_failure(self):
  2005. # The internal code did not preserve the previous exception when
  2006. # re-enabling garbage collection
  2007. try:
  2008. from resource import getrlimit, setrlimit, RLIMIT_NPROC
  2009. except ImportError as err:
  2010. self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD
  2011. limits = getrlimit(RLIMIT_NPROC)
  2012. [_, hard] = limits
  2013. setrlimit(RLIMIT_NPROC, (0, hard))
  2014. self.addCleanup(setrlimit, RLIMIT_NPROC, limits)
  2015. try:
  2016. subprocess.call([sys.executable, '-c', ''],
  2017. preexec_fn=lambda: None)
  2018. except BlockingIOError:
  2019. # Forking should raise EAGAIN, translated to BlockingIOError
  2020. pass
  2021. else:
  2022. self.skipTest('RLIMIT_NPROC had no effect; probably superuser')
  2023. def test_args_string(self):
  2024. # args is a string
  2025. fd, fname = tempfile.mkstemp()
  2026. # reopen in text mode
  2027. with open(fd, "w", errors="surrogateescape") as fobj:
  2028. fobj.write("#!%s\n" % support.unix_shell)
  2029. fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
  2030. sys.executable)
  2031. os.chmod(fname, 0o700)
  2032. p = subprocess.Popen(fname)
  2033. p.wait()
  2034. os.remove(fname)
  2035. self.assertEqual(p.returncode, 47)
  2036. def test_invalid_args(self):
  2037. # invalid arguments should raise ValueError
  2038. self.assertRaises(ValueError, subprocess.call,
  2039. [sys.executable, "-c",
  2040. "import sys; sys.exit(47)"],
  2041. startupinfo=47)
  2042. self.assertRaises(ValueError, subprocess.call,
  2043. [sys.executable, "-c",
  2044. "import sys; sys.exit(47)"],
  2045. creationflags=47)
  2046. def test_shell_sequence(self):
  2047. # Run command through the shell (sequence)
  2048. newenv = os.environ.copy()
  2049. newenv["FRUIT"] = "apple"
  2050. p = subprocess.Popen(["echo $FRUIT"], shell=1,
  2051. stdout=subprocess.PIPE,
  2052. env=newenv)
  2053. with p:
  2054. self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
  2055. def test_shell_string(self):
  2056. # Run command through the shell (string)
  2057. newenv = os.environ.copy()
  2058. newenv["FRUIT"] = "apple"
  2059. p = subprocess.Popen("echo $FRUIT", shell=1,
  2060. stdout=subprocess.PIPE,
  2061. env=newenv)
  2062. with p:
  2063. self.assertEqual(p.stdout.read().strip(b" \t\r\n\f"), b"apple")
  2064. def test_call_string(self):
  2065. # call() function with string argument on UNIX
  2066. fd, fname = tempfile.mkstemp()
  2067. # reopen in text mode
  2068. with open(fd, "w", errors="surrogateescape") as fobj:
  2069. fobj.write("#!%s\n" % support.unix_shell)
  2070. fobj.write("exec '%s' -c 'import sys; sys.exit(47)'\n" %
  2071. sys.executable)
  2072. os.chmod(fname, 0o700)
  2073. rc = subprocess.call(fname)
  2074. os.remove(fname)
  2075. self.assertEqual(rc, 47)
  2076. def test_specific_shell(self):
  2077. # Issue #9265: Incorrect name passed as arg[0].
  2078. shells = []
  2079. for prefix in ['/bin', '/usr/bin/', '/usr/local/bin']:
  2080. for name in ['bash', 'ksh']:
  2081. sh = os.path.join(prefix, name)
  2082. if os.path.isfile(sh):
  2083. shells.append(sh)
  2084. if not shells: # Will probably work for any shell but csh.
  2085. self.skipTest("bash or ksh required for this test")
  2086. sh = '/bin/sh'
  2087. if os.path.isfile(sh) and not os.path.islink(sh):
  2088. # Test will fail if /bin/sh is a symlink to csh.
  2089. shells.append(sh)
  2090. for sh in shells:
  2091. p = subprocess.Popen("echo $0", executable=sh, shell=True,
  2092. stdout=subprocess.PIPE)
  2093. with p:
  2094. self.assertEqual(p.stdout.read().strip(), bytes(sh, 'ascii'))
  2095. def _kill_process(self, method, *args):
  2096. # Do not inherit file handles from the parent.
  2097. # It should fix failures on some platforms.
  2098. # Also set the SIGINT handler to the default to make sure it's not
  2099. # being ignored (some tests rely on that.)
  2100. old_handler = signal.signal(signal.SIGINT, signal.default_int_handler)
  2101. try:
  2102. p = subprocess.Popen([sys.executable, "-c", """if 1:
  2103. import sys, time
  2104. sys.stdout.write('x\\n')
  2105. sys.stdout.flush()
  2106. time.sleep(30)
  2107. """],
  2108. close_fds=True,
  2109. stdin=subprocess.PIPE,
  2110. stdout=subprocess.PIPE,
  2111. stderr=subprocess.PIPE)
  2112. finally:
  2113. signal.signal(signal.SIGINT, old_handler)
  2114. # Wait for the interpreter to be completely initialized before
  2115. # sending any signal.
  2116. p.stdout.read(1)
  2117. getattr(p, method)(*args)
  2118. return p
  2119. @unittest.skipIf(sys.platform.startswith(('netbsd', 'openbsd')),
  2120. "Due to known OS bug (issue #16762)")
  2121. def _kill_dead_process(self, method, *args):
  2122. # Do not inherit file handles from the parent.
  2123. # It should fix failures on some platforms.
  2124. p = subprocess.Popen([sys.executable, "-c", """if 1:
  2125. import sys, time
  2126. sys.stdout.write('x\\n')
  2127. sys.stdout.flush()
  2128. """],
  2129. close_fds=True,
  2130. stdin=subprocess.PIPE,
  2131. stdout=subprocess.PIPE,
  2132. stderr=subprocess.PIPE)
  2133. # Wait for the interpreter to be completely initialized before
  2134. # sending any signal.
  2135. p.stdout.read(1)
  2136. # The process should end after this
  2137. time.sleep(1)
  2138. # This shouldn't raise even though the child is now dead
  2139. getattr(p, method)(*args)
  2140. p.communicate()
  2141. def test_send_signal(self):
  2142. p = self._kill_process('send_signal', signal.SIGINT)
  2143. _, stderr = p.communicate()
  2144. self.assertIn(b'KeyboardInterrupt', stderr)
  2145. self.assertNotEqual(p.wait(), 0)
  2146. def test_kill(self):
  2147. p = self._kill_process('kill')
  2148. _, stderr = p.communicate()
  2149. self.assertEqual(stderr, b'')
  2150. self.assertEqual(p.wait(), -signal.SIGKILL)
  2151. def test_terminate(self):
  2152. p = self._kill_process('terminate')
  2153. _, stderr = p.communicate()
  2154. self.assertEqual(stderr, b'')
  2155. self.assertEqual(p.wait(), -signal.SIGTERM)
  2156. def test_send_signal_dead(self):
  2157. # Sending a signal to a dead process
  2158. self._kill_dead_process('send_signal', signal.SIGINT)
  2159. def test_kill_dead(self):
  2160. # Killing a dead process
  2161. self._kill_dead_process('kill')
  2162. def test_terminate_dead(self):
  2163. # Terminating a dead process
  2164. self._kill_dead_process('terminate')
  2165. def _save_fds(self, save_fds):
  2166. fds = []
  2167. for fd in save_fds:
  2168. inheritable = os.get_inheritable(fd)
  2169. saved = os.dup(fd)
  2170. fds.append((fd, saved, inheritable))
  2171. return fds
  2172. def _restore_fds(self, fds):
  2173. for fd, saved, inheritable in fds:
  2174. os.dup2(saved, fd, inheritable=inheritable)
  2175. os.close(saved)
  2176. def check_close_std_fds(self, fds):
  2177. # Issue #9905: test that subprocess pipes still work properly with
  2178. # some standard fds closed
  2179. stdin = 0
  2180. saved_fds = self._save_fds(fds)
  2181. for fd, saved, inheritable in saved_fds:
  2182. if fd == 0:
  2183. stdin = saved
  2184. break
  2185. try:
  2186. for fd in fds:
  2187. os.close(fd)
  2188. out, err = subprocess.Popen([sys.executable, "-c",
  2189. 'import sys;'
  2190. 'sys.stdout.write("apple");'
  2191. 'sys.stdout.flush();'
  2192. 'sys.stderr.write("orange")'],
  2193. stdin=stdin,
  2194. stdout=subprocess.PIPE,
  2195. stderr=subprocess.PIPE).communicate()
  2196. self.assertEqual(out, b'apple')
  2197. self.assertEqual(err, b'orange')
  2198. finally:
  2199. self._restore_fds(saved_fds)
  2200. def test_close_fd_0(self):
  2201. self.check_close_std_fds([0])
  2202. def test_close_fd_1(self):
  2203. self.check_close_std_fds([1])
  2204. def test_close_fd_2(self):
  2205. self.check_close_std_fds([2])
  2206. def test_close_fds_0_1(self):
  2207. self.check_close_std_fds([0, 1])
  2208. def test_close_fds_0_2(self):
  2209. self.check_close_std_fds([0, 2])
  2210. def test_close_fds_1_2(self):
  2211. self.check_close_std_fds([1, 2])
  2212. def test_close_fds_0_1_2(self):
  2213. # Issue #10806: test that subprocess pipes still work properly with
  2214. # all standard fds closed.
  2215. self.check_close_std_fds([0, 1, 2])
  2216. def test_small_errpipe_write_fd(self):
  2217. """Issue #15798: Popen should work when stdio fds are available."""
  2218. new_stdin = os.dup(0)
  2219. new_stdout = os.dup(1)
  2220. try:
  2221. os.close(0)
  2222. os.close(1)
  2223. # Side test: if errpipe_write fails to have its CLOEXEC
  2224. # flag set this should cause the parent to think the exec
  2225. # failed. Extremely unlikely: everyone supports CLOEXEC.
  2226. subprocess.Popen([
  2227. sys.executable, "-c",
  2228. "print('AssertionError:0:CLOEXEC failure.')"]).wait()
  2229. finally:
  2230. # Restore original stdin and stdout
  2231. os.dup2(new_stdin, 0)
  2232. os.dup2(new_stdout, 1)
  2233. os.close(new_stdin)
  2234. os.close(new_stdout)
  2235. def test_remapping_std_fds(self):
  2236. # open up some temporary files
  2237. temps = [tempfile.mkstemp() for i in range(3)]
  2238. try:
  2239. temp_fds = [fd for fd, fname in temps]
  2240. # unlink the files -- we won't need to reopen them
  2241. for fd, fname in temps:
  2242. os.unlink(fname)
  2243. # write some data to what will become stdin, and rewind
  2244. os.write(temp_fds[1], b"STDIN")
  2245. os.lseek(temp_fds[1], 0, 0)
  2246. # move the standard file descriptors out of the way
  2247. saved_fds = self._save_fds(range(3))
  2248. try:
  2249. # duplicate the file objects over the standard fd's
  2250. for fd, temp_fd in enumerate(temp_fds):
  2251. os.dup2(temp_fd, fd)
  2252. # now use those files in the "wrong" order, so that subprocess
  2253. # has to rearrange them in the child
  2254. p = subprocess.Popen([sys.executable, "-c",
  2255. 'import sys; got = sys.stdin.read();'
  2256. 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
  2257. stdin=temp_fds[1],
  2258. stdout=temp_fds[2],
  2259. stderr=temp_fds[0])
  2260. p.wait()
  2261. finally:
  2262. self._restore_fds(saved_fds)
  2263. for fd in temp_fds:
  2264. os.lseek(fd, 0, 0)
  2265. out = os.read(temp_fds[2], 1024)
  2266. err = os.read(temp_fds[0], 1024).strip()
  2267. self.assertEqual(out, b"got STDIN")
  2268. self.assertEqual(err, b"err")
  2269. finally:
  2270. for fd in temp_fds:
  2271. os.close(fd)
  2272. def check_swap_fds(self, stdin_no, stdout_no, stderr_no):
  2273. # open up some temporary files
  2274. temps = [tempfile.mkstemp() for i in range(3)]
  2275. temp_fds = [fd for fd, fname in temps]
  2276. try:
  2277. # unlink the files -- we won't need to reopen them
  2278. for fd, fname in temps:
  2279. os.unlink(fname)
  2280. # save a copy of the standard file descriptors
  2281. saved_fds = self._save_fds(range(3))
  2282. try:
  2283. # duplicate the temp files over the standard fd's 0, 1, 2
  2284. for fd, temp_fd in enumerate(temp_fds):
  2285. os.dup2(temp_fd, fd)
  2286. # write some data to what will become stdin, and rewind
  2287. os.write(stdin_no, b"STDIN")
  2288. os.lseek(stdin_no, 0, 0)
  2289. # now use those files in the given order, so that subprocess
  2290. # has to rearrange them in the child
  2291. p = subprocess.Popen([sys.executable, "-c",
  2292. 'import sys; got = sys.stdin.read();'
  2293. 'sys.stdout.write("got %s"%got); sys.stderr.write("err")'],
  2294. stdin=stdin_no,
  2295. stdout=stdout_no,
  2296. stderr=stderr_no)
  2297. p.wait()
  2298. for fd in temp_fds:
  2299. os.lseek(fd, 0, 0)
  2300. out = os.read(stdout_no, 1024)
  2301. err = os.read(stderr_no, 1024).strip()
  2302. finally:
  2303. self._restore_fds(saved_fds)
  2304. self.assertEqual(out, b"got STDIN")
  2305. self.assertEqual(err, b"err")
  2306. finally:
  2307. for fd in temp_fds:
  2308. os.close(fd)
  2309. # When duping fds, if there arises a situation where one of the fds is
  2310. # either 0, 1 or 2, it is possible that it is overwritten (#12607).
  2311. # This tests all combinations of this.
  2312. def test_swap_fds(self):
  2313. self.check_swap_fds(0, 1, 2)
  2314. self.check_swap_fds(0, 2, 1)
  2315. self.check_swap_fds(1, 0, 2)
  2316. self.check_swap_fds(1, 2, 0)
  2317. self.check_swap_fds(2, 0, 1)
  2318. self.check_swap_fds(2, 1, 0)
  2319. def _check_swap_std_fds_with_one_closed(self, from_fds, to_fds):
  2320. saved_fds = self._save_fds(range(3))
  2321. try:
  2322. for from_fd in from_fds:
  2323. with tempfile.TemporaryFile() as f:
  2324. os.dup2(f.fileno(), from_fd)
  2325. fd_to_close = (set(range(3)) - set(from_fds)).pop()
  2326. os.close(fd_to_close)
  2327. arg_names = ['stdin', 'stdout', 'stderr']
  2328. kwargs = {}
  2329. for from_fd, to_fd in zip(from_fds, to_fds):
  2330. kwargs[arg_names[to_fd]] = from_fd
  2331. code = textwrap.dedent(r'''
  2332. import os, sys
  2333. skipped_fd = int(sys.argv[1])
  2334. for fd in range(3):
  2335. if fd != skipped_fd:
  2336. os.write(fd, str(fd).encode('ascii'))
  2337. ''')
  2338. skipped_fd = (set(range(3)) - set(to_fds)).pop()
  2339. rc = subprocess.call([sys.executable, '-c', code, str(skipped_fd)],
  2340. **kwargs)
  2341. self.assertEqual(rc, 0)
  2342. for from_fd, to_fd in zip(from_fds, to_fds):
  2343. os.lseek(from_fd, 0, os.SEEK_SET)
  2344. read_bytes = os.read(from_fd, 1024)
  2345. read_fds = list(map(int, read_bytes.decode('ascii')))
  2346. msg = textwrap.dedent(f"""
  2347. When testing {from_fds} to {to_fds} redirection,
  2348. parent descriptor {from_fd} got redirected
  2349. to descriptor(s) {read_fds} instead of descriptor {to_fd}.
  2350. """)
  2351. self.assertEqual([to_fd], read_fds, msg)
  2352. finally:
  2353. self._restore_fds(saved_fds)
  2354. # Check that subprocess can remap std fds correctly even
  2355. # if one of them is closed (#32844).
  2356. def test_swap_std_fds_with_one_closed(self):
  2357. for from_fds in itertools.combinations(range(3), 2):
  2358. for to_fds in itertools.permutations(range(3), 2):
  2359. self._check_swap_std_fds_with_one_closed(from_fds, to_fds)
  2360. def test_surrogates_error_message(self):
  2361. def prepare():
  2362. raise ValueError("surrogate:\uDCff")
  2363. try:
  2364. subprocess.call(
  2365. ZERO_RETURN_CMD,
  2366. preexec_fn=prepare)
  2367. except ValueError as err:
  2368. # Pure Python implementations keeps the message
  2369. self.assertIsNone(subprocess._fork_exec)
  2370. self.assertEqual(str(err), "surrogate:\uDCff")
  2371. except subprocess.SubprocessError as err:
  2372. # _posixsubprocess uses a default message
  2373. self.assertIsNotNone(subprocess._fork_exec)
  2374. self.assertEqual(str(err), "Exception occurred in preexec_fn.")
  2375. else:
  2376. self.fail("Expected ValueError or subprocess.SubprocessError")
  2377. def test_undecodable_env(self):
  2378. for key, value in (('test', 'abc\uDCFF'), ('test\uDCFF', '42')):
  2379. encoded_value = value.encode("ascii", "surrogateescape")
  2380. # test str with surrogates
  2381. script = "import os; print(ascii(os.getenv(%s)))" % repr(key)
  2382. env = os.environ.copy()
  2383. env[key] = value
  2384. # Use C locale to get ASCII for the locale encoding to force
  2385. # surrogate-escaping of \xFF in the child process
  2386. env['LC_ALL'] = 'C'
  2387. decoded_value = value
  2388. stdout = subprocess.check_output(
  2389. [sys.executable, "-c", script],
  2390. env=env)
  2391. stdout = stdout.rstrip(b'\n\r')
  2392. self.assertEqual(stdout.decode('ascii'), ascii(decoded_value))
  2393. # test bytes
  2394. key = key.encode("ascii", "surrogateescape")
  2395. script = "import os; print(ascii(os.getenvb(%s)))" % repr(key)
  2396. env = os.environ.copy()
  2397. env[key] = encoded_value
  2398. stdout = subprocess.check_output(
  2399. [sys.executable, "-c", script],
  2400. env=env)
  2401. stdout = stdout.rstrip(b'\n\r')
  2402. self.assertEqual(stdout.decode('ascii'), ascii(encoded_value))
  2403. def test_bytes_program(self):
  2404. abs_program = os.fsencode(ZERO_RETURN_CMD[0])
  2405. args = list(ZERO_RETURN_CMD[1:])
  2406. path, program = os.path.split(ZERO_RETURN_CMD[0])
  2407. program = os.fsencode(program)
  2408. # absolute bytes path
  2409. exitcode = subprocess.call([abs_program]+args)
  2410. self.assertEqual(exitcode, 0)
  2411. # absolute bytes path as a string
  2412. cmd = b"'%s' %s" % (abs_program, " ".join(args).encode("utf-8"))
  2413. exitcode = subprocess.call(cmd, shell=True)
  2414. self.assertEqual(exitcode, 0)
  2415. # bytes program, unicode PATH
  2416. env = os.environ.copy()
  2417. env["PATH"] = path
  2418. exitcode = subprocess.call([program]+args, env=env)
  2419. self.assertEqual(exitcode, 0)
  2420. # bytes program, bytes PATH
  2421. envb = os.environb.copy()
  2422. envb[b"PATH"] = os.fsencode(path)
  2423. exitcode = subprocess.call([program]+args, env=envb)
  2424. self.assertEqual(exitcode, 0)
  2425. def test_pipe_cloexec(self):
  2426. sleeper = support.findfile("input_reader.py", subdir="subprocessdata")
  2427. fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
  2428. p1 = subprocess.Popen([sys.executable, sleeper],
  2429. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  2430. stderr=subprocess.PIPE, close_fds=False)
  2431. self.addCleanup(p1.communicate, b'')
  2432. p2 = subprocess.Popen([sys.executable, fd_status],
  2433. stdout=subprocess.PIPE, close_fds=False)
  2434. output, error = p2.communicate()
  2435. result_fds = set(map(int, output.split(b',')))
  2436. unwanted_fds = set([p1.stdin.fileno(), p1.stdout.fileno(),
  2437. p1.stderr.fileno()])
  2438. self.assertFalse(result_fds & unwanted_fds,
  2439. "Expected no fds from %r to be open in child, "
  2440. "found %r" %
  2441. (unwanted_fds, result_fds & unwanted_fds))
  2442. def test_pipe_cloexec_real_tools(self):
  2443. qcat = support.findfile("qcat.py", subdir="subprocessdata")
  2444. qgrep = support.findfile("qgrep.py", subdir="subprocessdata")
  2445. subdata = b'zxcvbn'
  2446. data = subdata * 4 + b'\n'
  2447. p1 = subprocess.Popen([sys.executable, qcat],
  2448. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  2449. close_fds=False)
  2450. p2 = subprocess.Popen([sys.executable, qgrep, subdata],
  2451. stdin=p1.stdout, stdout=subprocess.PIPE,
  2452. close_fds=False)
  2453. self.addCleanup(p1.wait)
  2454. self.addCleanup(p2.wait)
  2455. def kill_p1():
  2456. try:
  2457. p1.terminate()
  2458. except ProcessLookupError:
  2459. pass
  2460. def kill_p2():
  2461. try:
  2462. p2.terminate()
  2463. except ProcessLookupError:
  2464. pass
  2465. self.addCleanup(kill_p1)
  2466. self.addCleanup(kill_p2)
  2467. p1.stdin.write(data)
  2468. p1.stdin.close()
  2469. readfiles, ignored1, ignored2 = select.select([p2.stdout], [], [], 10)
  2470. self.assertTrue(readfiles, "The child hung")
  2471. self.assertEqual(p2.stdout.read(), data)
  2472. p1.stdout.close()
  2473. p2.stdout.close()
  2474. def test_close_fds(self):
  2475. fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
  2476. fds = os.pipe()
  2477. self.addCleanup(os.close, fds[0])
  2478. self.addCleanup(os.close, fds[1])
  2479. open_fds = set(fds)
  2480. # add a bunch more fds
  2481. for _ in range(9):
  2482. fd = os.open(os.devnull, os.O_RDONLY)
  2483. self.addCleanup(os.close, fd)
  2484. open_fds.add(fd)
  2485. for fd in open_fds:
  2486. os.set_inheritable(fd, True)
  2487. p = subprocess.Popen([sys.executable, fd_status],
  2488. stdout=subprocess.PIPE, close_fds=False)
  2489. output, ignored = p.communicate()
  2490. remaining_fds = set(map(int, output.split(b',')))
  2491. self.assertEqual(remaining_fds & open_fds, open_fds,
  2492. "Some fds were closed")
  2493. p = subprocess.Popen([sys.executable, fd_status],
  2494. stdout=subprocess.PIPE, close_fds=True)
  2495. output, ignored = p.communicate()
  2496. remaining_fds = set(map(int, output.split(b',')))
  2497. self.assertFalse(remaining_fds & open_fds,
  2498. "Some fds were left open")
  2499. self.assertIn(1, remaining_fds, "Subprocess failed")
  2500. # Keep some of the fd's we opened open in the subprocess.
  2501. # This tests _posixsubprocess.c's proper handling of fds_to_keep.
  2502. fds_to_keep = set(open_fds.pop() for _ in range(8))
  2503. p = subprocess.Popen([sys.executable, fd_status],
  2504. stdout=subprocess.PIPE, close_fds=True,
  2505. pass_fds=fds_to_keep)
  2506. output, ignored = p.communicate()
  2507. remaining_fds = set(map(int, output.split(b',')))
  2508. self.assertFalse((remaining_fds - fds_to_keep) & open_fds,
  2509. "Some fds not in pass_fds were left open")
  2510. self.assertIn(1, remaining_fds, "Subprocess failed")
  2511. @unittest.skipIf(sys.platform.startswith("freebsd") and
  2512. os.stat("/dev").st_dev == os.stat("/dev/fd").st_dev,
  2513. "Requires fdescfs mounted on /dev/fd on FreeBSD")
  2514. def test_close_fds_when_max_fd_is_lowered(self):
  2515. """Confirm that issue21618 is fixed (may fail under valgrind)."""
  2516. fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
  2517. # This launches the meat of the test in a child process to
  2518. # avoid messing with the larger unittest processes maximum
  2519. # number of file descriptors.
  2520. # This process launches:
  2521. # +--> Process that lowers its RLIMIT_NOFILE aftr setting up
  2522. # a bunch of high open fds above the new lower rlimit.
  2523. # Those are reported via stdout before launching a new
  2524. # process with close_fds=False to run the actual test:
  2525. # +--> The TEST: This one launches a fd_status.py
  2526. # subprocess with close_fds=True so we can find out if
  2527. # any of the fds above the lowered rlimit are still open.
  2528. p = subprocess.Popen([sys.executable, '-c', textwrap.dedent(
  2529. '''
  2530. import os, resource, subprocess, sys, textwrap
  2531. open_fds = set()
  2532. # Add a bunch more fds to pass down.
  2533. for _ in range(40):
  2534. fd = os.open(os.devnull, os.O_RDONLY)
  2535. open_fds.add(fd)
  2536. # Leave a two pairs of low ones available for use by the
  2537. # internal child error pipe and the stdout pipe.
  2538. # We also leave 10 more open as some Python buildbots run into
  2539. # "too many open files" errors during the test if we do not.
  2540. for fd in sorted(open_fds)[:14]:
  2541. os.close(fd)
  2542. open_fds.remove(fd)
  2543. for fd in open_fds:
  2544. #self.addCleanup(os.close, fd)
  2545. os.set_inheritable(fd, True)
  2546. max_fd_open = max(open_fds)
  2547. # Communicate the open_fds to the parent unittest.TestCase process.
  2548. print(','.join(map(str, sorted(open_fds))))
  2549. sys.stdout.flush()
  2550. rlim_cur, rlim_max = resource.getrlimit(resource.RLIMIT_NOFILE)
  2551. try:
  2552. # 29 is lower than the highest fds we are leaving open.
  2553. resource.setrlimit(resource.RLIMIT_NOFILE, (29, rlim_max))
  2554. # Launch a new Python interpreter with our low fd rlim_cur that
  2555. # inherits open fds above that limit. It then uses subprocess
  2556. # with close_fds=True to get a report of open fds in the child.
  2557. # An explicit list of fds to check is passed to fd_status.py as
  2558. # letting fd_status rely on its default logic would miss the
  2559. # fds above rlim_cur as it normally only checks up to that limit.
  2560. subprocess.Popen(
  2561. [sys.executable, '-c',
  2562. textwrap.dedent("""
  2563. import subprocess, sys
  2564. subprocess.Popen([sys.executable, %r] +
  2565. [str(x) for x in range({max_fd})],
  2566. close_fds=True).wait()
  2567. """.format(max_fd=max_fd_open+1))],
  2568. close_fds=False).wait()
  2569. finally:
  2570. resource.setrlimit(resource.RLIMIT_NOFILE, (rlim_cur, rlim_max))
  2571. ''' % fd_status)], stdout=subprocess.PIPE)
  2572. output, unused_stderr = p.communicate()
  2573. output_lines = output.splitlines()
  2574. self.assertEqual(len(output_lines), 2,
  2575. msg="expected exactly two lines of output:\n%r" % output)
  2576. opened_fds = set(map(int, output_lines[0].strip().split(b',')))
  2577. remaining_fds = set(map(int, output_lines[1].strip().split(b',')))
  2578. self.assertFalse(remaining_fds & opened_fds,
  2579. msg="Some fds were left open.")
  2580. # Mac OS X Tiger (10.4) has a kernel bug: sometimes, the file
  2581. # descriptor of a pipe closed in the parent process is valid in the
  2582. # child process according to fstat(), but the mode of the file
  2583. # descriptor is invalid, and read or write raise an error.
  2584. @support.requires_mac_ver(10, 5)
  2585. def test_pass_fds(self):
  2586. fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
  2587. open_fds = set()
  2588. for x in range(5):
  2589. fds = os.pipe()
  2590. self.addCleanup(os.close, fds[0])
  2591. self.addCleanup(os.close, fds[1])
  2592. os.set_inheritable(fds[0], True)
  2593. os.set_inheritable(fds[1], True)
  2594. open_fds.update(fds)
  2595. for fd in open_fds:
  2596. p = subprocess.Popen([sys.executable, fd_status],
  2597. stdout=subprocess.PIPE, close_fds=True,
  2598. pass_fds=(fd, ))
  2599. output, ignored = p.communicate()
  2600. remaining_fds = set(map(int, output.split(b',')))
  2601. to_be_closed = open_fds - {fd}
  2602. self.assertIn(fd, remaining_fds, "fd to be passed not passed")
  2603. self.assertFalse(remaining_fds & to_be_closed,
  2604. "fd to be closed passed")
  2605. # pass_fds overrides close_fds with a warning.
  2606. with self.assertWarns(RuntimeWarning) as context:
  2607. self.assertFalse(subprocess.call(
  2608. ZERO_RETURN_CMD,
  2609. close_fds=False, pass_fds=(fd, )))
  2610. self.assertIn('overriding close_fds', str(context.warning))
  2611. def test_pass_fds_inheritable(self):
  2612. script = support.findfile("fd_status.py", subdir="subprocessdata")
  2613. inheritable, non_inheritable = os.pipe()
  2614. self.addCleanup(os.close, inheritable)
  2615. self.addCleanup(os.close, non_inheritable)
  2616. os.set_inheritable(inheritable, True)
  2617. os.set_inheritable(non_inheritable, False)
  2618. pass_fds = (inheritable, non_inheritable)
  2619. args = [sys.executable, script]
  2620. args += list(map(str, pass_fds))
  2621. p = subprocess.Popen(args,
  2622. stdout=subprocess.PIPE, close_fds=True,
  2623. pass_fds=pass_fds)
  2624. output, ignored = p.communicate()
  2625. fds = set(map(int, output.split(b',')))
  2626. # the inheritable file descriptor must be inherited, so its inheritable
  2627. # flag must be set in the child process after fork() and before exec()
  2628. self.assertEqual(fds, set(pass_fds), "output=%a" % output)
  2629. # inheritable flag must not be changed in the parent process
  2630. self.assertEqual(os.get_inheritable(inheritable), True)
  2631. self.assertEqual(os.get_inheritable(non_inheritable), False)
  2632. # bpo-32270: Ensure that descriptors specified in pass_fds
  2633. # are inherited even if they are used in redirections.
  2634. # Contributed by @izbyshev.
  2635. def test_pass_fds_redirected(self):
  2636. """Regression test for https://bugs.python.org/issue32270."""
  2637. fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
  2638. pass_fds = []
  2639. for _ in range(2):
  2640. fd = os.open(os.devnull, os.O_RDWR)
  2641. self.addCleanup(os.close, fd)
  2642. pass_fds.append(fd)
  2643. stdout_r, stdout_w = os.pipe()
  2644. self.addCleanup(os.close, stdout_r)
  2645. self.addCleanup(os.close, stdout_w)
  2646. pass_fds.insert(1, stdout_w)
  2647. with subprocess.Popen([sys.executable, fd_status],
  2648. stdin=pass_fds[0],
  2649. stdout=pass_fds[1],
  2650. stderr=pass_fds[2],
  2651. close_fds=True,
  2652. pass_fds=pass_fds):
  2653. output = os.read(stdout_r, 1024)
  2654. fds = {int(num) for num in output.split(b',')}
  2655. self.assertEqual(fds, {0, 1, 2} | frozenset(pass_fds), f"output={output!a}")
  2656. def test_stdout_stdin_are_single_inout_fd(self):
  2657. with io.open(os.devnull, "r+") as inout:
  2658. p = subprocess.Popen(ZERO_RETURN_CMD,
  2659. stdout=inout, stdin=inout)
  2660. p.wait()
  2661. def test_stdout_stderr_are_single_inout_fd(self):
  2662. with io.open(os.devnull, "r+") as inout:
  2663. p = subprocess.Popen(ZERO_RETURN_CMD,
  2664. stdout=inout, stderr=inout)
  2665. p.wait()
  2666. def test_stderr_stdin_are_single_inout_fd(self):
  2667. with io.open(os.devnull, "r+") as inout:
  2668. p = subprocess.Popen(ZERO_RETURN_CMD,
  2669. stderr=inout, stdin=inout)
  2670. p.wait()
  2671. def test_wait_when_sigchild_ignored(self):
  2672. # NOTE: sigchild_ignore.py may not be an effective test on all OSes.
  2673. sigchild_ignore = support.findfile("sigchild_ignore.py",
  2674. subdir="subprocessdata")
  2675. p = subprocess.Popen([sys.executable, sigchild_ignore],
  2676. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  2677. stdout, stderr = p.communicate()
  2678. self.assertEqual(0, p.returncode, "sigchild_ignore.py exited"
  2679. " non-zero with this error:\n%s" %
  2680. stderr.decode('utf-8'))
  2681. def test_select_unbuffered(self):
  2682. # Issue #11459: bufsize=0 should really set the pipes as
  2683. # unbuffered (and therefore let select() work properly).
  2684. select = import_helper.import_module("select")
  2685. p = subprocess.Popen([sys.executable, "-c",
  2686. 'import sys;'
  2687. 'sys.stdout.write("apple")'],
  2688. stdout=subprocess.PIPE,
  2689. bufsize=0)
  2690. f = p.stdout
  2691. self.addCleanup(f.close)
  2692. try:
  2693. self.assertEqual(f.read(4), b"appl")
  2694. self.assertIn(f, select.select([f], [], [], 0.0)[0])
  2695. finally:
  2696. p.wait()
  2697. def test_zombie_fast_process_del(self):
  2698. # Issue #12650: on Unix, if Popen.__del__() was called before the
  2699. # process exited, it wouldn't be added to subprocess._active, and would
  2700. # remain a zombie.
  2701. # spawn a Popen, and delete its reference before it exits
  2702. p = subprocess.Popen([sys.executable, "-c",
  2703. 'import sys, time;'
  2704. 'time.sleep(0.2)'],
  2705. stdout=subprocess.PIPE,
  2706. stderr=subprocess.PIPE)
  2707. self.addCleanup(p.stdout.close)
  2708. self.addCleanup(p.stderr.close)
  2709. ident = id(p)
  2710. pid = p.pid
  2711. with warnings_helper.check_warnings(('', ResourceWarning)):
  2712. p = None
  2713. if mswindows:
  2714. # subprocess._active is not used on Windows and is set to None.
  2715. self.assertIsNone(subprocess._active)
  2716. else:
  2717. # check that p is in the active processes list
  2718. self.assertIn(ident, [id(o) for o in subprocess._active])
  2719. def test_leak_fast_process_del_killed(self):
  2720. # Issue #12650: on Unix, if Popen.__del__() was called before the
  2721. # process exited, and the process got killed by a signal, it would never
  2722. # be removed from subprocess._active, which triggered a FD and memory
  2723. # leak.
  2724. # spawn a Popen, delete its reference and kill it
  2725. p = subprocess.Popen([sys.executable, "-c",
  2726. 'import time;'
  2727. 'time.sleep(3)'],
  2728. stdout=subprocess.PIPE,
  2729. stderr=subprocess.PIPE)
  2730. self.addCleanup(p.stdout.close)
  2731. self.addCleanup(p.stderr.close)
  2732. ident = id(p)
  2733. pid = p.pid
  2734. with warnings_helper.check_warnings(('', ResourceWarning)):
  2735. p = None
  2736. support.gc_collect() # For PyPy or other GCs.
  2737. os.kill(pid, signal.SIGKILL)
  2738. if mswindows:
  2739. # subprocess._active is not used on Windows and is set to None.
  2740. self.assertIsNone(subprocess._active)
  2741. else:
  2742. # check that p is in the active processes list
  2743. self.assertIn(ident, [id(o) for o in subprocess._active])
  2744. # let some time for the process to exit, and create a new Popen: this
  2745. # should trigger the wait() of p
  2746. time.sleep(0.2)
  2747. with self.assertRaises(OSError):
  2748. with subprocess.Popen(NONEXISTING_CMD,
  2749. stdout=subprocess.PIPE,
  2750. stderr=subprocess.PIPE) as proc:
  2751. pass
  2752. # p should have been wait()ed on, and removed from the _active list
  2753. self.assertRaises(OSError, os.waitpid, pid, 0)
  2754. if mswindows:
  2755. # subprocess._active is not used on Windows and is set to None.
  2756. self.assertIsNone(subprocess._active)
  2757. else:
  2758. self.assertNotIn(ident, [id(o) for o in subprocess._active])
  2759. def test_close_fds_after_preexec(self):
  2760. fd_status = support.findfile("fd_status.py", subdir="subprocessdata")
  2761. # this FD is used as dup2() target by preexec_fn, and should be closed
  2762. # in the child process
  2763. fd = os.dup(1)
  2764. self.addCleanup(os.close, fd)
  2765. p = subprocess.Popen([sys.executable, fd_status],
  2766. stdout=subprocess.PIPE, close_fds=True,
  2767. preexec_fn=lambda: os.dup2(1, fd))
  2768. output, ignored = p.communicate()
  2769. remaining_fds = set(map(int, output.split(b',')))
  2770. self.assertNotIn(fd, remaining_fds)
  2771. @support.cpython_only
  2772. def test_fork_exec(self):
  2773. # Issue #22290: fork_exec() must not crash on memory allocation failure
  2774. # or other errors
  2775. import _posixsubprocess
  2776. gc_enabled = gc.isenabled()
  2777. try:
  2778. # Use a preexec function and enable the garbage collector
  2779. # to force fork_exec() to re-enable the garbage collector
  2780. # on error.
  2781. func = lambda: None
  2782. gc.enable()
  2783. for args, exe_list, cwd, env_list in (
  2784. (123, [b"exe"], None, [b"env"]),
  2785. ([b"arg"], 123, None, [b"env"]),
  2786. ([b"arg"], [b"exe"], 123, [b"env"]),
  2787. ([b"arg"], [b"exe"], None, 123),
  2788. ):
  2789. with self.assertRaises(TypeError) as err:
  2790. _posixsubprocess.fork_exec(
  2791. args, exe_list,
  2792. True, (), cwd, env_list,
  2793. -1, -1, -1, -1,
  2794. 1, 2, 3, 4,
  2795. True, True, 0,
  2796. False, [], 0, -1,
  2797. func, False)
  2798. # Attempt to prevent
  2799. # "TypeError: fork_exec() takes exactly N arguments (M given)"
  2800. # from passing the test. More refactoring to have us start
  2801. # with a valid *args list, confirm a good call with that works
  2802. # before mutating it in various ways to ensure that bad calls
  2803. # with individual arg type errors raise a typeerror would be
  2804. # ideal. Saving that for a future PR...
  2805. self.assertNotIn('takes exactly', str(err.exception))
  2806. finally:
  2807. if not gc_enabled:
  2808. gc.disable()
  2809. @support.cpython_only
  2810. def test_fork_exec_sorted_fd_sanity_check(self):
  2811. # Issue #23564: sanity check the fork_exec() fds_to_keep sanity check.
  2812. import _posixsubprocess
  2813. class BadInt:
  2814. first = True
  2815. def __init__(self, value):
  2816. self.value = value
  2817. def __int__(self):
  2818. if self.first:
  2819. self.first = False
  2820. return self.value
  2821. raise ValueError
  2822. gc_enabled = gc.isenabled()
  2823. try:
  2824. gc.enable()
  2825. for fds_to_keep in (
  2826. (-1, 2, 3, 4, 5), # Negative number.
  2827. ('str', 4), # Not an int.
  2828. (18, 23, 42, 2**63), # Out of range.
  2829. (5, 4), # Not sorted.
  2830. (6, 7, 7, 8), # Duplicate.
  2831. (BadInt(1), BadInt(2)),
  2832. ):
  2833. with self.assertRaises(
  2834. ValueError,
  2835. msg='fds_to_keep={}'.format(fds_to_keep)) as c:
  2836. _posixsubprocess.fork_exec(
  2837. [b"false"], [b"false"],
  2838. True, fds_to_keep, None, [b"env"],
  2839. -1, -1, -1, -1,
  2840. 1, 2, 3, 4,
  2841. True, True, 0,
  2842. None, None, None, -1,
  2843. None, True)
  2844. self.assertIn('fds_to_keep', str(c.exception))
  2845. finally:
  2846. if not gc_enabled:
  2847. gc.disable()
  2848. def test_communicate_BrokenPipeError_stdin_close(self):
  2849. # By not setting stdout or stderr or a timeout we force the fast path
  2850. # that just calls _stdin_write() internally due to our mock.
  2851. proc = subprocess.Popen(ZERO_RETURN_CMD)
  2852. with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
  2853. mock_proc_stdin.close.side_effect = BrokenPipeError
  2854. proc.communicate() # Should swallow BrokenPipeError from close.
  2855. mock_proc_stdin.close.assert_called_with()
  2856. def test_communicate_BrokenPipeError_stdin_write(self):
  2857. # By not setting stdout or stderr or a timeout we force the fast path
  2858. # that just calls _stdin_write() internally due to our mock.
  2859. proc = subprocess.Popen(ZERO_RETURN_CMD)
  2860. with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
  2861. mock_proc_stdin.write.side_effect = BrokenPipeError
  2862. proc.communicate(b'stuff') # Should swallow the BrokenPipeError.
  2863. mock_proc_stdin.write.assert_called_once_with(b'stuff')
  2864. mock_proc_stdin.close.assert_called_once_with()
  2865. def test_communicate_BrokenPipeError_stdin_flush(self):
  2866. # Setting stdin and stdout forces the ._communicate() code path.
  2867. # python -h exits faster than python -c pass (but spams stdout).
  2868. proc = subprocess.Popen([sys.executable, '-h'],
  2869. stdin=subprocess.PIPE,
  2870. stdout=subprocess.PIPE)
  2871. with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin, \
  2872. open(os.devnull, 'wb') as dev_null:
  2873. mock_proc_stdin.flush.side_effect = BrokenPipeError
  2874. # because _communicate registers a selector using proc.stdin...
  2875. mock_proc_stdin.fileno.return_value = dev_null.fileno()
  2876. # _communicate() should swallow BrokenPipeError from flush.
  2877. proc.communicate(b'stuff')
  2878. mock_proc_stdin.flush.assert_called_once_with()
  2879. def test_communicate_BrokenPipeError_stdin_close_with_timeout(self):
  2880. # Setting stdin and stdout forces the ._communicate() code path.
  2881. # python -h exits faster than python -c pass (but spams stdout).
  2882. proc = subprocess.Popen([sys.executable, '-h'],
  2883. stdin=subprocess.PIPE,
  2884. stdout=subprocess.PIPE)
  2885. with proc, mock.patch.object(proc, 'stdin') as mock_proc_stdin:
  2886. mock_proc_stdin.close.side_effect = BrokenPipeError
  2887. # _communicate() should swallow BrokenPipeError from close.
  2888. proc.communicate(timeout=999)
  2889. mock_proc_stdin.close.assert_called_once_with()
  2890. @unittest.skipUnless(_testcapi is not None
  2891. and hasattr(_testcapi, 'W_STOPCODE'),
  2892. 'need _testcapi.W_STOPCODE')
  2893. def test_stopped(self):
  2894. """Test wait() behavior when waitpid returns WIFSTOPPED; issue29335."""
  2895. args = ZERO_RETURN_CMD
  2896. proc = subprocess.Popen(args)
  2897. # Wait until the real process completes to avoid zombie process
  2898. support.wait_process(proc.pid, exitcode=0)
  2899. status = _testcapi.W_STOPCODE(3)
  2900. with mock.patch('subprocess.os.waitpid', return_value=(proc.pid, status)):
  2901. returncode = proc.wait()
  2902. self.assertEqual(returncode, -3)
  2903. def test_send_signal_race(self):
  2904. # bpo-38630: send_signal() must poll the process exit status to reduce
  2905. # the risk of sending the signal to the wrong process.
  2906. proc = subprocess.Popen(ZERO_RETURN_CMD)
  2907. # wait until the process completes without using the Popen APIs.
  2908. support.wait_process(proc.pid, exitcode=0)
  2909. # returncode is still None but the process completed.
  2910. self.assertIsNone(proc.returncode)
  2911. with mock.patch("os.kill") as mock_kill:
  2912. proc.send_signal(signal.SIGTERM)
  2913. # send_signal() didn't call os.kill() since the process already
  2914. # completed.
  2915. mock_kill.assert_not_called()
  2916. # Don't check the returncode value: the test reads the exit status,
  2917. # so Popen failed to read it and uses a default returncode instead.
  2918. self.assertIsNotNone(proc.returncode)
  2919. def test_send_signal_race2(self):
  2920. # bpo-40550: the process might exist between the returncode check and
  2921. # the kill operation
  2922. p = subprocess.Popen([sys.executable, '-c', 'exit(1)'])
  2923. # wait for process to exit
  2924. while not p.returncode:
  2925. p.poll()
  2926. with mock.patch.object(p, 'poll', new=lambda: None):
  2927. p.returncode = None
  2928. p.send_signal(signal.SIGTERM)
  2929. p.kill()
  2930. def test_communicate_repeated_call_after_stdout_close(self):
  2931. proc = subprocess.Popen([sys.executable, '-c',
  2932. 'import os, time; os.close(1), time.sleep(2)'],
  2933. stdout=subprocess.PIPE)
  2934. while True:
  2935. try:
  2936. proc.communicate(timeout=0.1)
  2937. return
  2938. except subprocess.TimeoutExpired:
  2939. pass
  2940. @unittest.skipUnless(mswindows, "Windows specific tests")
  2941. class Win32ProcessTestCase(BaseTestCase):
  2942. def test_startupinfo(self):
  2943. # startupinfo argument
  2944. # We uses hardcoded constants, because we do not want to
  2945. # depend on win32all.
  2946. STARTF_USESHOWWINDOW = 1
  2947. SW_MAXIMIZE = 3
  2948. startupinfo = subprocess.STARTUPINFO()
  2949. startupinfo.dwFlags = STARTF_USESHOWWINDOW
  2950. startupinfo.wShowWindow = SW_MAXIMIZE
  2951. # Since Python is a console process, it won't be affected
  2952. # by wShowWindow, but the argument should be silently
  2953. # ignored
  2954. subprocess.call(ZERO_RETURN_CMD,
  2955. startupinfo=startupinfo)
  2956. def test_startupinfo_keywords(self):
  2957. # startupinfo argument
  2958. # We use hardcoded constants, because we do not want to
  2959. # depend on win32all.
  2960. STARTF_USERSHOWWINDOW = 1
  2961. SW_MAXIMIZE = 3
  2962. startupinfo = subprocess.STARTUPINFO(
  2963. dwFlags=STARTF_USERSHOWWINDOW,
  2964. wShowWindow=SW_MAXIMIZE
  2965. )
  2966. # Since Python is a console process, it won't be affected
  2967. # by wShowWindow, but the argument should be silently
  2968. # ignored
  2969. subprocess.call(ZERO_RETURN_CMD,
  2970. startupinfo=startupinfo)
  2971. def test_startupinfo_copy(self):
  2972. # bpo-34044: Popen must not modify input STARTUPINFO structure
  2973. startupinfo = subprocess.STARTUPINFO()
  2974. startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
  2975. startupinfo.wShowWindow = subprocess.SW_HIDE
  2976. # Call Popen() twice with the same startupinfo object to make sure
  2977. # that it's not modified
  2978. for _ in range(2):
  2979. cmd = ZERO_RETURN_CMD
  2980. with open(os.devnull, 'w') as null:
  2981. proc = subprocess.Popen(cmd,
  2982. stdout=null,
  2983. stderr=subprocess.STDOUT,
  2984. startupinfo=startupinfo)
  2985. with proc:
  2986. proc.communicate()
  2987. self.assertEqual(proc.returncode, 0)
  2988. self.assertEqual(startupinfo.dwFlags,
  2989. subprocess.STARTF_USESHOWWINDOW)
  2990. self.assertIsNone(startupinfo.hStdInput)
  2991. self.assertIsNone(startupinfo.hStdOutput)
  2992. self.assertIsNone(startupinfo.hStdError)
  2993. self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
  2994. self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []})
  2995. def test_creationflags(self):
  2996. # creationflags argument
  2997. CREATE_NEW_CONSOLE = 16
  2998. sys.stderr.write(" a DOS box should flash briefly ...\n")
  2999. subprocess.call(sys.executable +
  3000. ' -c "import time; time.sleep(0.25)"',
  3001. creationflags=CREATE_NEW_CONSOLE)
  3002. def test_invalid_args(self):
  3003. # invalid arguments should raise ValueError
  3004. self.assertRaises(ValueError, subprocess.call,
  3005. [sys.executable, "-c",
  3006. "import sys; sys.exit(47)"],
  3007. preexec_fn=lambda: 1)
  3008. @support.cpython_only
  3009. def test_issue31471(self):
  3010. # There shouldn't be an assertion failure in Popen() in case the env
  3011. # argument has a bad keys() method.
  3012. class BadEnv(dict):
  3013. keys = None
  3014. with self.assertRaises(TypeError):
  3015. subprocess.Popen(ZERO_RETURN_CMD, env=BadEnv())
  3016. def test_close_fds(self):
  3017. # close file descriptors
  3018. rc = subprocess.call([sys.executable, "-c",
  3019. "import sys; sys.exit(47)"],
  3020. close_fds=True)
  3021. self.assertEqual(rc, 47)
  3022. def test_close_fds_with_stdio(self):
  3023. import msvcrt
  3024. fds = os.pipe()
  3025. self.addCleanup(os.close, fds[0])
  3026. self.addCleanup(os.close, fds[1])
  3027. handles = []
  3028. for fd in fds:
  3029. os.set_inheritable(fd, True)
  3030. handles.append(msvcrt.get_osfhandle(fd))
  3031. p = subprocess.Popen([sys.executable, "-c",
  3032. "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
  3033. stdout=subprocess.PIPE, close_fds=False)
  3034. stdout, stderr = p.communicate()
  3035. self.assertEqual(p.returncode, 0)
  3036. int(stdout.strip()) # Check that stdout is an integer
  3037. p = subprocess.Popen([sys.executable, "-c",
  3038. "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
  3039. stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
  3040. stdout, stderr = p.communicate()
  3041. self.assertEqual(p.returncode, 1)
  3042. self.assertIn(b"OSError", stderr)
  3043. # The same as the previous call, but with an empty handle_list
  3044. handle_list = []
  3045. startupinfo = subprocess.STARTUPINFO()
  3046. startupinfo.lpAttributeList = {"handle_list": handle_list}
  3047. p = subprocess.Popen([sys.executable, "-c",
  3048. "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
  3049. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  3050. startupinfo=startupinfo, close_fds=True)
  3051. stdout, stderr = p.communicate()
  3052. self.assertEqual(p.returncode, 1)
  3053. self.assertIn(b"OSError", stderr)
  3054. # Check for a warning due to using handle_list and close_fds=False
  3055. with warnings_helper.check_warnings((".*overriding close_fds",
  3056. RuntimeWarning)):
  3057. startupinfo = subprocess.STARTUPINFO()
  3058. startupinfo.lpAttributeList = {"handle_list": handles[:]}
  3059. p = subprocess.Popen([sys.executable, "-c",
  3060. "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
  3061. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  3062. startupinfo=startupinfo, close_fds=False)
  3063. stdout, stderr = p.communicate()
  3064. self.assertEqual(p.returncode, 0)
  3065. def test_empty_attribute_list(self):
  3066. startupinfo = subprocess.STARTUPINFO()
  3067. startupinfo.lpAttributeList = {}
  3068. subprocess.call(ZERO_RETURN_CMD,
  3069. startupinfo=startupinfo)
  3070. def test_empty_handle_list(self):
  3071. startupinfo = subprocess.STARTUPINFO()
  3072. startupinfo.lpAttributeList = {"handle_list": []}
  3073. subprocess.call(ZERO_RETURN_CMD,
  3074. startupinfo=startupinfo)
  3075. def test_shell_sequence(self):
  3076. # Run command through the shell (sequence)
  3077. newenv = os.environ.copy()
  3078. newenv["FRUIT"] = "physalis"
  3079. p = subprocess.Popen(["set"], shell=1,
  3080. stdout=subprocess.PIPE,
  3081. env=newenv)
  3082. with p:
  3083. self.assertIn(b"physalis", p.stdout.read())
  3084. def test_shell_string(self):
  3085. # Run command through the shell (string)
  3086. newenv = os.environ.copy()
  3087. newenv["FRUIT"] = "physalis"
  3088. p = subprocess.Popen("set", shell=1,
  3089. stdout=subprocess.PIPE,
  3090. env=newenv)
  3091. with p:
  3092. self.assertIn(b"physalis", p.stdout.read())
  3093. def test_shell_encodings(self):
  3094. # Run command through the shell (string)
  3095. for enc in ['ansi', 'oem']:
  3096. newenv = os.environ.copy()
  3097. newenv["FRUIT"] = "physalis"
  3098. p = subprocess.Popen("set", shell=1,
  3099. stdout=subprocess.PIPE,
  3100. env=newenv,
  3101. encoding=enc)
  3102. with p:
  3103. self.assertIn("physalis", p.stdout.read(), enc)
  3104. def test_call_string(self):
  3105. # call() function with string argument on Windows
  3106. rc = subprocess.call(sys.executable +
  3107. ' -c "import sys; sys.exit(47)"')
  3108. self.assertEqual(rc, 47)
  3109. def _kill_process(self, method, *args):
  3110. # Some win32 buildbot raises EOFError if stdin is inherited
  3111. p = subprocess.Popen([sys.executable, "-c", """if 1:
  3112. import sys, time
  3113. sys.stdout.write('x\\n')
  3114. sys.stdout.flush()
  3115. time.sleep(30)
  3116. """],
  3117. stdin=subprocess.PIPE,
  3118. stdout=subprocess.PIPE,
  3119. stderr=subprocess.PIPE)
  3120. with p:
  3121. # Wait for the interpreter to be completely initialized before
  3122. # sending any signal.
  3123. p.stdout.read(1)
  3124. getattr(p, method)(*args)
  3125. _, stderr = p.communicate()
  3126. self.assertEqual(stderr, b'')
  3127. returncode = p.wait()
  3128. self.assertNotEqual(returncode, 0)
  3129. def _kill_dead_process(self, method, *args):
  3130. p = subprocess.Popen([sys.executable, "-c", """if 1:
  3131. import sys, time
  3132. sys.stdout.write('x\\n')
  3133. sys.stdout.flush()
  3134. sys.exit(42)
  3135. """],
  3136. stdin=subprocess.PIPE,
  3137. stdout=subprocess.PIPE,
  3138. stderr=subprocess.PIPE)
  3139. with p:
  3140. # Wait for the interpreter to be completely initialized before
  3141. # sending any signal.
  3142. p.stdout.read(1)
  3143. # The process should end after this
  3144. time.sleep(1)
  3145. # This shouldn't raise even though the child is now dead
  3146. getattr(p, method)(*args)
  3147. _, stderr = p.communicate()
  3148. self.assertEqual(stderr, b'')
  3149. rc = p.wait()
  3150. self.assertEqual(rc, 42)
  3151. def test_send_signal(self):
  3152. self._kill_process('send_signal', signal.SIGTERM)
  3153. def test_kill(self):
  3154. self._kill_process('kill')
  3155. def test_terminate(self):
  3156. self._kill_process('terminate')
  3157. def test_send_signal_dead(self):
  3158. self._kill_dead_process('send_signal', signal.SIGTERM)
  3159. def test_kill_dead(self):
  3160. self._kill_dead_process('kill')
  3161. def test_terminate_dead(self):
  3162. self._kill_dead_process('terminate')
  3163. class MiscTests(unittest.TestCase):
  3164. class RecordingPopen(subprocess.Popen):
  3165. """A Popen that saves a reference to each instance for testing."""
  3166. instances_created = []
  3167. def __init__(self, *args, **kwargs):
  3168. super().__init__(*args, **kwargs)
  3169. self.instances_created.append(self)
  3170. @mock.patch.object(subprocess.Popen, "_communicate")
  3171. def _test_keyboardinterrupt_no_kill(self, popener, mock__communicate,
  3172. **kwargs):
  3173. """Fake a SIGINT happening during Popen._communicate() and ._wait().
  3174. This avoids the need to actually try and get test environments to send
  3175. and receive signals reliably across platforms. The net effect of a ^C
  3176. happening during a blocking subprocess execution which we want to clean
  3177. up from is a KeyboardInterrupt coming out of communicate() or wait().
  3178. """
  3179. mock__communicate.side_effect = KeyboardInterrupt
  3180. try:
  3181. with mock.patch.object(subprocess.Popen, "_wait") as mock__wait:
  3182. # We patch out _wait() as no signal was involved so the
  3183. # child process isn't actually going to exit rapidly.
  3184. mock__wait.side_effect = KeyboardInterrupt
  3185. with mock.patch.object(subprocess, "Popen",
  3186. self.RecordingPopen):
  3187. with self.assertRaises(KeyboardInterrupt):
  3188. popener([sys.executable, "-c",
  3189. "import time\ntime.sleep(9)\nimport sys\n"
  3190. "sys.stderr.write('\\n!runaway child!\\n')"],
  3191. stdout=subprocess.DEVNULL, **kwargs)
  3192. for call in mock__wait.call_args_list[1:]:
  3193. self.assertNotEqual(
  3194. call, mock.call(timeout=None),
  3195. "no open-ended wait() after the first allowed: "
  3196. f"{mock__wait.call_args_list}")
  3197. sigint_calls = []
  3198. for call in mock__wait.call_args_list:
  3199. if call == mock.call(timeout=0.25): # from Popen.__init__
  3200. sigint_calls.append(call)
  3201. self.assertLessEqual(mock__wait.call_count, 2,
  3202. msg=mock__wait.call_args_list)
  3203. self.assertEqual(len(sigint_calls), 1,
  3204. msg=mock__wait.call_args_list)
  3205. finally:
  3206. # cleanup the forgotten (due to our mocks) child process
  3207. process = self.RecordingPopen.instances_created.pop()
  3208. process.kill()
  3209. process.wait()
  3210. self.assertEqual([], self.RecordingPopen.instances_created)
  3211. def test_call_keyboardinterrupt_no_kill(self):
  3212. self._test_keyboardinterrupt_no_kill(subprocess.call, timeout=6.282)
  3213. def test_run_keyboardinterrupt_no_kill(self):
  3214. self._test_keyboardinterrupt_no_kill(subprocess.run, timeout=6.282)
  3215. def test_context_manager_keyboardinterrupt_no_kill(self):
  3216. def popen_via_context_manager(*args, **kwargs):
  3217. with subprocess.Popen(*args, **kwargs) as unused_process:
  3218. raise KeyboardInterrupt # Test how __exit__ handles ^C.
  3219. self._test_keyboardinterrupt_no_kill(popen_via_context_manager)
  3220. def test_getoutput(self):
  3221. self.assertEqual(subprocess.getoutput('echo xyzzy'), 'xyzzy')
  3222. self.assertEqual(subprocess.getstatusoutput('echo xyzzy'),
  3223. (0, 'xyzzy'))
  3224. # we use mkdtemp in the next line to create an empty directory
  3225. # under our exclusive control; from that, we can invent a pathname
  3226. # that we _know_ won't exist. This is guaranteed to fail.
  3227. dir = None
  3228. try:
  3229. dir = tempfile.mkdtemp()
  3230. name = os.path.join(dir, "foo")
  3231. status, output = subprocess.getstatusoutput(
  3232. ("type " if mswindows else "cat ") + name)
  3233. self.assertNotEqual(status, 0)
  3234. finally:
  3235. if dir is not None:
  3236. os.rmdir(dir)
  3237. def test__all__(self):
  3238. """Ensure that __all__ is populated properly."""
  3239. intentionally_excluded = {"list2cmdline", "Handle", "pwd", "grp", "fcntl"}
  3240. exported = set(subprocess.__all__)
  3241. possible_exports = set()
  3242. import types
  3243. for name, value in subprocess.__dict__.items():
  3244. if name.startswith('_'):
  3245. continue
  3246. if isinstance(value, (types.ModuleType,)):
  3247. continue
  3248. possible_exports.add(name)
  3249. self.assertEqual(exported, possible_exports - intentionally_excluded)
  3250. @unittest.skipUnless(hasattr(selectors, 'PollSelector'),
  3251. "Test needs selectors.PollSelector")
  3252. class ProcessTestCaseNoPoll(ProcessTestCase):
  3253. def setUp(self):
  3254. self.orig_selector = subprocess._PopenSelector
  3255. subprocess._PopenSelector = selectors.SelectSelector
  3256. ProcessTestCase.setUp(self)
  3257. def tearDown(self):
  3258. subprocess._PopenSelector = self.orig_selector
  3259. ProcessTestCase.tearDown(self)
  3260. @unittest.skipUnless(mswindows, "Windows-specific tests")
  3261. class CommandsWithSpaces (BaseTestCase):
  3262. def setUp(self):
  3263. super().setUp()
  3264. f, fname = tempfile.mkstemp(".py", "te st")
  3265. self.fname = fname.lower ()
  3266. os.write(f, b"import sys;"
  3267. b"sys.stdout.write('%d %s' % (len(sys.argv), [a.lower () for a in sys.argv]))"
  3268. )
  3269. os.close(f)
  3270. def tearDown(self):
  3271. os.remove(self.fname)
  3272. super().tearDown()
  3273. def with_spaces(self, *args, **kwargs):
  3274. kwargs['stdout'] = subprocess.PIPE
  3275. p = subprocess.Popen(*args, **kwargs)
  3276. with p:
  3277. self.assertEqual(
  3278. p.stdout.read ().decode("mbcs"),
  3279. "2 [%r, 'ab cd']" % self.fname
  3280. )
  3281. def test_shell_string_with_spaces(self):
  3282. # call() function with string argument with spaces on Windows
  3283. self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
  3284. "ab cd"), shell=1)
  3285. def test_shell_sequence_with_spaces(self):
  3286. # call() function with sequence argument with spaces on Windows
  3287. self.with_spaces([sys.executable, self.fname, "ab cd"], shell=1)
  3288. def test_noshell_string_with_spaces(self):
  3289. # call() function with string argument with spaces on Windows
  3290. self.with_spaces('"%s" "%s" "%s"' % (sys.executable, self.fname,
  3291. "ab cd"))
  3292. def test_noshell_sequence_with_spaces(self):
  3293. # call() function with sequence argument with spaces on Windows
  3294. self.with_spaces([sys.executable, self.fname, "ab cd"])
  3295. class ContextManagerTests(BaseTestCase):
  3296. def test_pipe(self):
  3297. with subprocess.Popen([sys.executable, "-c",
  3298. "import sys;"
  3299. "sys.stdout.write('stdout');"
  3300. "sys.stderr.write('stderr');"],
  3301. stdout=subprocess.PIPE,
  3302. stderr=subprocess.PIPE) as proc:
  3303. self.assertEqual(proc.stdout.read(), b"stdout")
  3304. self.assertEqual(proc.stderr.read(), b"stderr")
  3305. self.assertTrue(proc.stdout.closed)
  3306. self.assertTrue(proc.stderr.closed)
  3307. def test_returncode(self):
  3308. with subprocess.Popen([sys.executable, "-c",
  3309. "import sys; sys.exit(100)"]) as proc:
  3310. pass
  3311. # __exit__ calls wait(), so the returncode should be set
  3312. self.assertEqual(proc.returncode, 100)
  3313. def test_communicate_stdin(self):
  3314. with subprocess.Popen([sys.executable, "-c",
  3315. "import sys;"
  3316. "sys.exit(sys.stdin.read() == 'context')"],
  3317. stdin=subprocess.PIPE) as proc:
  3318. proc.communicate(b"context")
  3319. self.assertEqual(proc.returncode, 1)
  3320. def test_invalid_args(self):
  3321. with self.assertRaises(NONEXISTING_ERRORS):
  3322. with subprocess.Popen(NONEXISTING_CMD,
  3323. stdout=subprocess.PIPE,
  3324. stderr=subprocess.PIPE) as proc:
  3325. pass
  3326. def test_broken_pipe_cleanup(self):
  3327. """Broken pipe error should not prevent wait() (Issue 21619)"""
  3328. proc = subprocess.Popen(ZERO_RETURN_CMD,
  3329. stdin=subprocess.PIPE,
  3330. bufsize=support.PIPE_MAX_SIZE*2)
  3331. proc = proc.__enter__()
  3332. # Prepare to send enough data to overflow any OS pipe buffering and
  3333. # guarantee a broken pipe error. Data is held in BufferedWriter
  3334. # buffer until closed.
  3335. proc.stdin.write(b'x' * support.PIPE_MAX_SIZE)
  3336. self.assertIsNone(proc.returncode)
  3337. # EPIPE expected under POSIX; EINVAL under Windows
  3338. self.assertRaises(OSError, proc.__exit__, None, None, None)
  3339. self.assertEqual(proc.returncode, 0)
  3340. self.assertTrue(proc.stdin.closed)
  3341. if __name__ == "__main__":
  3342. unittest.main()