-
Notifications
You must be signed in to change notification settings - Fork 934
/
subprocess.py
2058 lines (1785 loc) · 82.2 KB
/
subprocess.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Cooperative ``subprocess`` module.
.. caution:: On POSIX platforms, this module is not usable from native
threads other than the main thread; attempting to do so will raise
a :exc:`TypeError`. This module depends on libev's fork watchers.
On POSIX systems, fork watchers are implemented using signals, and
the thread to which process-directed signals are delivered `is not
defined`_. Because each native thread has its own gevent/libev
loop, this means that a fork watcher registered with one loop
(thread) may never see the signal about a child it spawned if the
signal is sent to a different thread.
.. note:: The interface of this module is intended to match that of
the standard library :mod:`subprocess` module (with many backwards
compatible extensions from Python 3 backported to Python 2). There
are some small differences between the Python 2 and Python 3
versions of that module (the Python 2 ``TimeoutExpired`` exception,
notably, extends ``Timeout`` and there is no ``SubprocessError``) and between the
POSIX and Windows versions. The HTML documentation here can only
describe one version; for definitive documentation, see the
standard library or the source code.
.. _is not defined: http://www.linuxprogrammingblog.com/all-about-linux-signals?page=11
"""
from __future__ import absolute_import, print_function
# Can we split this up to make it cleaner? See https://github.com/gevent/gevent/issues/748
# pylint: disable=too-many-lines
# Most of this we inherit from the standard lib
# pylint: disable=bare-except,too-many-locals,too-many-statements,attribute-defined-outside-init
# pylint: disable=too-many-branches,too-many-instance-attributes
# Most of this is cross-platform
# pylint: disable=no-member,expression-not-assigned,unused-argument,unused-variable
import errno
import gc
import os
import signal
import sys
import traceback
# Python 3.9
try:
from types import GenericAlias
except ImportError:
GenericAlias = None
try:
import grp
except ImportError:
grp = None
try:
import pwd
except ImportError:
pwd = None
from gevent.event import AsyncResult
from gevent.hub import _get_hub_noargs as get_hub
from gevent.hub import linkproxy
from gevent.hub import sleep
from gevent.hub import getcurrent
from gevent._compat import integer_types, string_types, xrange
from gevent._compat import PY3
from gevent._compat import PY35
from gevent._compat import PY36
from gevent._compat import PY37
from gevent._compat import PY38
from gevent._compat import PY311
from gevent._compat import PYPY
from gevent._compat import reraise
from gevent._compat import fsdecode
from gevent._compat import fsencode
from gevent._compat import PathLike
from gevent._util import _NONE
from gevent._util import copy_globals
from gevent.greenlet import Greenlet, joinall
spawn = Greenlet.spawn
import subprocess as __subprocess__
# Standard functions and classes that this module re-implements in a gevent-aware way.
__implements__ = [
'Popen',
'call',
'check_call',
'check_output',
]
if PY3 and not sys.platform.startswith('win32'):
__implements__.append("_posixsubprocess")
_posixsubprocess = None
# Some symbols we define that we expect to export;
# useful for static analysis
PIPE = "PIPE should be imported"
# Standard functions and classes that this module re-imports.
__imports__ = [
'PIPE',
'STDOUT',
'CalledProcessError',
# Windows:
'CREATE_NEW_CONSOLE',
'CREATE_NEW_PROCESS_GROUP',
'STD_INPUT_HANDLE',
'STD_OUTPUT_HANDLE',
'STD_ERROR_HANDLE',
'SW_HIDE',
'STARTF_USESTDHANDLES',
'STARTF_USESHOWWINDOW',
]
__extra__ = [
'MAXFD',
'_eintr_retry_call',
'STARTUPINFO',
'pywintypes',
'list2cmdline',
'_subprocess',
'_winapi',
# Python 2.5 does not have _subprocess, so we don't use it
# XXX We don't run on Py 2.5 anymore; can/could/should we use _subprocess?
# It's only used on mswindows
'WAIT_OBJECT_0',
'WaitForSingleObject',
'GetExitCodeProcess',
'GetStdHandle',
'CreatePipe',
'DuplicateHandle',
'GetCurrentProcess',
'DUPLICATE_SAME_ACCESS',
'GetModuleFileName',
'GetVersion',
'CreateProcess',
'INFINITE',
'TerminateProcess',
'STILL_ACTIVE',
# These were added for 3.5, but we make them available everywhere.
'run',
'CompletedProcess',
]
if PY3:
__imports__ += [
'DEVNULL',
'getstatusoutput',
'getoutput',
'SubprocessError',
'TimeoutExpired',
]
else:
__extra__.append("TimeoutExpired")
if PY35:
__extra__.remove('run')
__extra__.remove('CompletedProcess')
__implements__.append('run')
__implements__.append('CompletedProcess')
# Removed in Python 3.5; this is the exact code that was removed:
# https://hg.python.org/cpython/rev/f98b0a5e5ef5
__extra__.remove('MAXFD')
try:
MAXFD = os.sysconf("SC_OPEN_MAX")
except:
MAXFD = 256
if PY36:
# This was added to __all__ for windows in 3.6
__extra__.remove('STARTUPINFO')
__imports__.append('STARTUPINFO')
if PY37:
__imports__.extend([
'ABOVE_NORMAL_PRIORITY_CLASS', 'BELOW_NORMAL_PRIORITY_CLASS',
'HIGH_PRIORITY_CLASS', 'IDLE_PRIORITY_CLASS',
'NORMAL_PRIORITY_CLASS',
'REALTIME_PRIORITY_CLASS',
'CREATE_NO_WINDOW', 'DETACHED_PROCESS',
'CREATE_DEFAULT_ERROR_MODE',
'CREATE_BREAKAWAY_FROM_JOB'
])
if PY38:
# Using os.posix_spawn() to start subprocesses
# bypasses our child watchers on certain operating systems,
# and with certain library versions. Possibly the right
# fix is to monkey-patch os.posix_spawn like we do os.fork?
# These have no effect, they're just here to match the stdlib.
# TODO: When available, given a monkey patch on them, I think
# we ought to be able to use them if the stdlib has identified them
# as suitable.
__implements__.extend([
'_use_posix_spawn',
])
def _use_posix_spawn():
return False
_USE_POSIX_SPAWN = False
if __subprocess__._USE_POSIX_SPAWN:
__implements__.extend([
'_USE_POSIX_SPAWN',
])
else:
__imports__.extend([
'_USE_POSIX_SPAWN',
])
if PY311:
# Python 3.11 added some module-level attributes to control the
# use of vfork. The docs specifically say that you should not try to read
# them, only set them, so we don't provide them.
#
# Python 3.11 also added a test, test_surrogates_error_message, that behaves
# differently based on whether or not the pure python implementation of forking
# is in use, or the one written in C from _posixsubprocess. Obviously we don't call
# that, so we need to make us look like a pure python version; it checks that this attribute
# is none for that.
_fork_exec = None
__implements__.extend([
'_fork_exec',
] if sys.platform != 'win32' else [
])
actually_imported = copy_globals(__subprocess__, globals(),
only_names=__imports__,
ignore_missing_names=True)
# anything we couldn't import from here we may need to find
# elsewhere
__extra__.extend(set(__imports__).difference(set(actually_imported)))
__imports__ = actually_imported
del actually_imported
# In Python 3 on Windows, a lot of the functions previously
# in _subprocess moved to _winapi
_subprocess = getattr(__subprocess__, '_subprocess', _NONE)
_winapi = getattr(__subprocess__, '_winapi', _NONE)
_attr_resolution_order = [__subprocess__, _subprocess, _winapi]
for name in list(__extra__):
if name in globals():
continue
value = _NONE
for place in _attr_resolution_order:
value = getattr(place, name, _NONE)
if value is not _NONE:
break
if value is _NONE:
__extra__.remove(name)
else:
globals()[name] = value
del _attr_resolution_order
__all__ = __implements__ + __imports__
# Some other things we want to document
for _x in ('run', 'CompletedProcess', 'TimeoutExpired'):
if _x not in __all__:
__all__.append(_x)
mswindows = sys.platform == 'win32'
if mswindows:
import msvcrt # pylint: disable=import-error
if PY3:
class Handle(int):
closed = False
def Close(self):
if not self.closed:
self.closed = True
_winapi.CloseHandle(self)
def Detach(self):
if not self.closed:
self.closed = True
return int(self)
raise ValueError("already closed")
def __repr__(self):
return "Handle(%d)" % int(self)
__del__ = Close
__str__ = __repr__
else:
import fcntl
import pickle
from gevent import monkey
fork = monkey.get_original('os', 'fork')
from gevent.os import fork_and_watch
try:
BrokenPipeError # pylint:disable=used-before-assignment
except NameError: # Python 2
class BrokenPipeError(Exception):
"Never raised, never caught."
def call(*popenargs, **kwargs):
"""
call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) -> returncode
Run command with arguments. Wait for command to complete or
timeout, then return the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = call(["ls", "-l"])
.. versionchanged:: 1.2a1
The ``timeout`` keyword argument is now accepted on all supported
versions of Python (not just Python 3) and if it expires will raise a
:exc:`TimeoutExpired` exception (under Python 2 this is a subclass of :exc:`~.Timeout`).
"""
timeout = kwargs.pop('timeout', None)
with Popen(*popenargs, **kwargs) as p:
try:
return p.wait(timeout=timeout, _raise_exc=True)
except:
p.kill()
p.wait()
raise
def check_call(*popenargs, **kwargs):
"""
check_call(args, *, stdin=None, stdout=None, stderr=None, shell=False, timeout=None) -> 0
Run command with arguments. Wait for command to complete. If
the exit code was zero then return, otherwise raise
:exc:`CalledProcessError`. The ``CalledProcessError`` object will have the
return code in the returncode attribute.
The arguments are the same as for the Popen constructor. Example::
retcode = check_call(["ls", "-l"])
"""
retcode = call(*popenargs, **kwargs)
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd) # pylint:disable=undefined-variable
return 0
def check_output(*popenargs, **kwargs):
r"""
check_output(args, *, input=None, stdin=None, stderr=None, shell=False, universal_newlines=False, timeout=None) -> output
Run command with arguments and return its output.
If the exit code was non-zero it raises a :exc:`CalledProcessError`. The
``CalledProcessError`` object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example::
>>> check_output(["ls", "-1", "/dev/null"])
'/dev/null\n'
The ``stdout`` argument is not allowed as it is used internally.
To capture standard error in the result, use ``stderr=STDOUT``::
>>> print(check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT).decode('ascii').strip())
ls: non_existent_file: No such file or directory
There is an additional optional argument, "input", allowing you to
pass a string to the subprocess's stdin. If you use this argument
you may not also use the Popen constructor's "stdin" argument, as
it too will be used internally. Example::
>>> check_output(["sed", "-e", "s/foo/bar/"],
... input=b"when in the course of fooman events\n")
'when in the course of barman events\n'
If ``universal_newlines=True`` is passed, the return value will be a
string rather than bytes.
.. versionchanged:: 1.2a1
The ``timeout`` keyword argument is now accepted on all supported
versions of Python (not just Python 3) and if it expires will raise a
:exc:`TimeoutExpired` exception (under Python 2 this is a subclass of :exc:`~.Timeout`).
.. versionchanged:: 1.2a1
The ``input`` keyword argument is now accepted on all supported
versions of Python, not just Python 3
.. versionchanged:: 22.08.0
Passing the ``check`` keyword argument is forbidden, just as in Python 3.11.
"""
timeout = kwargs.pop('timeout', None)
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
if 'check' in kwargs:
raise ValueError('check argument not allowed, it will be overridden.')
if 'input' in kwargs:
if 'stdin' in kwargs:
raise ValueError('stdin and input arguments may not both be used.')
inputdata = kwargs['input']
del kwargs['input']
kwargs['stdin'] = PIPE
else:
inputdata = None
with Popen(*popenargs, stdout=PIPE, **kwargs) as process:
try:
output, unused_err = process.communicate(inputdata, timeout=timeout)
except TimeoutExpired:
process.kill()
output, unused_err = process.communicate()
raise TimeoutExpired(process.args, timeout, output=output)
except:
process.kill()
process.wait()
raise
retcode = process.poll()
if retcode:
# pylint:disable=undefined-variable
raise CalledProcessError(retcode, process.args, output=output)
return output
_PLATFORM_DEFAULT_CLOSE_FDS = object()
if 'TimeoutExpired' not in globals():
# Python 2
# Make TimeoutExpired inherit from _Timeout so it can be caught
# the way we used to throw things (except Timeout), but make sure it doesn't
# init a timer. Note that we can't have a fake 'SubprocessError' that inherits
# from exception, because we need TimeoutExpired to just be a BaseException for
# bwc.
from gevent.timeout import Timeout as _Timeout
class TimeoutExpired(_Timeout):
"""
This exception is raised when the timeout expires while waiting for
a child process in `communicate`.
Under Python 2, this is a gevent extension with the same name as the
Python 3 class for source-code forward compatibility. However, it extends
:class:`gevent.timeout.Timeout` for backwards compatibility (because
we used to just raise a plain ``Timeout``); note that ``Timeout`` is a
``BaseException``, *not* an ``Exception``.
.. versionadded:: 1.2a1
"""
def __init__(self, cmd, timeout, output=None):
_Timeout.__init__(self, None)
self.cmd = cmd
self.seconds = timeout
self.output = output
@property
def timeout(self):
return self.seconds
def __str__(self):
return ("Command '%s' timed out after %s seconds" %
(self.cmd, self.timeout))
if hasattr(os, 'set_inheritable'):
_set_inheritable = os.set_inheritable
else:
_set_inheritable = lambda i, v: True
def FileObject(*args, **kwargs):
# Defer importing FileObject until we need it
# to allow it to be configured more easily.
from gevent.fileobject import FileObject as _FileObject
if not PY3:
# Make write behave like the old Python 2 file
# write and loop to consume output, even when not
# buffered.
__FileObject = _FileObject
def _FileObject(*args, **kwargs):
kwargs['atomic_write'] = True
return __FileObject(*args, **kwargs)
globals()['FileObject'] = _FileObject
return _FileObject(*args)
class _CommunicatingGreenlets(object):
# At most, exactly one of these objects may be created
# for a given Popen object. This ensures that only one background
# greenlet at a time will be reading from the file object. This matters because
# if a timeout exception is raised, the user may call back into communicate() to
# get the output (usually after killing the process; see run()). We must not
# lose output in that case (Python 3 specifically documents that raising a timeout
# doesn't lose output). Also, attempting to read from a pipe while it's already
# being read from results in `RuntimeError: reentrant call in io.BufferedReader`;
# the same thing happens if you attempt to close() it while that's in progress.
__slots__ = (
'stdin',
'stdout',
'stderr',
'_all_greenlets',
)
def __init__(self, popen, input_data):
self.stdin = self.stdout = self.stderr = None
if popen.stdin: # Even if no data, we need to close
self.stdin = spawn(self._write_and_close, popen.stdin, input_data)
# If the timeout parameter is used, and the caller calls back after
# getting a TimeoutExpired exception, we can wind up with multiple
# greenlets trying to run and read from and close stdout/stderr.
# That's bad because it can lead to 'RuntimeError: reentrant call in io.BufferedReader'.
# We can't just kill the previous greenlets when a timeout happens,
# though, because we risk losing the output collected by that greenlet
# (and Python 3, where timeout is an official parameter, explicitly says
# that no output should be lost in the event of a timeout.) Instead, we're
# watching for the exception and ignoring it. It's not elegant,
# but it works
if popen.stdout:
self.stdout = spawn(self._read_and_close, popen.stdout)
if popen.stderr:
self.stderr = spawn(self._read_and_close, popen.stderr)
all_greenlets = []
for g in self.stdin, self.stdout, self.stderr:
if g is not None:
all_greenlets.append(g)
self._all_greenlets = tuple(all_greenlets)
def __iter__(self):
return iter(self._all_greenlets)
def __bool__(self):
return bool(self._all_greenlets)
__nonzero__ = __bool__
def __len__(self):
return len(self._all_greenlets)
@staticmethod
def _write_and_close(fobj, data):
try:
if data:
fobj.write(data)
if hasattr(fobj, 'flush'):
# 3.6 started expecting flush to be called.
fobj.flush()
except (OSError, IOError, BrokenPipeError) as ex:
# Test cases from the stdlib can raise BrokenPipeError
# without setting an errno value. This matters because
# Python 2 doesn't have a BrokenPipeError.
if isinstance(ex, BrokenPipeError) and ex.errno is None:
ex.errno = errno.EPIPE
if ex.errno not in (errno.EPIPE, errno.EINVAL):
raise
finally:
try:
fobj.close()
except EnvironmentError:
pass
@staticmethod
def _read_and_close(fobj):
try:
return fobj.read()
finally:
try:
fobj.close()
except EnvironmentError:
pass
class Popen(object):
"""
The underlying process creation and management in this module is
handled by the Popen class. It offers a lot of flexibility so that
developers are able to handle the less common cases not covered by
the convenience functions.
.. seealso:: :class:`subprocess.Popen`
This class should have the same interface as the standard library class.
.. caution::
The default values of some arguments, notably ``buffering``, differ
between Python 2 and Python 3. For the most consistent behaviour across
versions, it's best to explicitly pass the desired values.
.. caution::
On Python 2, the ``read`` method of the ``stdout`` and ``stderr`` attributes
will not be buffered unless buffering is explicitly requested (e.g., `bufsize=-1`).
This is different than the ``read`` method of the standard library attributes,
which will buffer internally even if no buffering has been requested. This
matches the Python 3 behaviour. For portability, please explicitly request
buffering if you want ``read(n)`` to return all ``n`` bytes, making more than
one system call if needed. See `issue 1701 <https://github.com/gevent/gevent/issues/1701>`_
for more context.
.. versionchanged:: 1.2a1
Instances can now be used as context managers under Python 2.7. Previously
this was restricted to Python 3.
.. versionchanged:: 1.2a1
Instances now save the ``args`` attribute under Python 2.7. Previously this was
restricted to Python 3.
.. versionchanged:: 1.2b1
Add the ``encoding`` and ``errors`` parameters for Python 3.
.. versionchanged:: 1.3a1
Accept "path-like" objects for the *cwd* parameter on all platforms.
This was added to Python 3.6. Previously with gevent, it only worked
on POSIX platforms on 3.6.
.. versionchanged:: 1.3a1
Add the ``text`` argument as a synonym for ``universal_newlines``,
as added on Python 3.7.
.. versionchanged:: 1.3a2
Allow the same keyword arguments under Python 2 as Python 3:
``pass_fds``, ``start_new_session``, ``restore_signals``, ``encoding``
and ``errors``. Under Python 2, ``encoding`` and ``errors`` are ignored
because native handling of universal newlines is used.
.. versionchanged:: 1.3a2
Under Python 2, ``restore_signals`` defaults to ``False``. Previously it
defaulted to ``True``, the same as it did in Python 3.
.. versionchanged:: 20.6.0
Add the *group*, *extra_groups*, *user*, and *umask* arguments. These
were added to Python 3.9, but are available in any gevent version, provided
the underlying platform support is present.
.. versionchanged:: 20.12.0
On Python 2 only, if unbuffered binary communication is requested,
the ``stdin`` attribute of this object will have a ``write`` method that
actually performs internal buffering and looping, similar to the standard library.
It guarantees to write all the data given to it in a single call (but internally
it may make many system calls and/or trips around the event loop to accomplish this).
See :issue:`1711`.
.. versionchanged:: 21.12.0
Added the ``pipesize`` argument for compatibility with Python 3.10.
This is ignored on all platforms.
.. versionchanged:: 22.08.0
Added the ``process_group`` and ``check`` arguments for compatibility with
Python 3.11.
"""
if GenericAlias is not None:
# 3.9, annoying typing is creeping everywhere.
__class_getitem__ = classmethod(GenericAlias)
# The value returned from communicate() when there was nothing to read.
# Changes if we're in text mode or universal newlines mode.
_communicate_empty_value = b''
def __init__(self, args,
bufsize=-1 if PY3 else 0,
executable=None,
stdin=None, stdout=None, stderr=None,
preexec_fn=None, close_fds=_PLATFORM_DEFAULT_CLOSE_FDS, shell=False,
cwd=None, env=None, universal_newlines=None,
startupinfo=None, creationflags=0,
restore_signals=PY3, start_new_session=False,
pass_fds=(),
# Added in 3.6. These are kept as ivars
encoding=None, errors=None,
# Added in 3.7. Not an ivar directly.
text=None,
# Added in 3.9
group=None, extra_groups=None, user=None,
umask=-1,
# Added in 3.10, but ignored.
pipesize=-1,
# Added in 3.11
process_group=None,
# gevent additions
threadpool=None):
self.encoding = encoding
self.errors = errors
hub = get_hub()
if bufsize is None:
# Python 2 doesn't allow None at all, but Python 3 treats
# it the same as the default. We do as well.
bufsize = -1 if PY3 else 0
if not isinstance(bufsize, integer_types):
raise TypeError("bufsize must be an integer")
if mswindows:
if preexec_fn is not None:
raise ValueError("preexec_fn is not supported on Windows "
"platforms")
if PY37:
if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
close_fds = True
else:
any_stdio_set = (stdin is not None or stdout is not None or
stderr is not None)
if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
if any_stdio_set:
close_fds = False
else:
close_fds = True
elif close_fds and any_stdio_set:
raise ValueError("close_fds is not supported on Windows "
"platforms if you redirect stdin/stdout/stderr")
if threadpool is None:
threadpool = hub.threadpool
self.threadpool = threadpool
self._waiting = False
else:
# POSIX
if close_fds is _PLATFORM_DEFAULT_CLOSE_FDS:
# close_fds has different defaults on Py3/Py2
if PY3: # pylint: disable=simplifiable-if-statement
close_fds = True
else:
close_fds = False
if pass_fds and not close_fds:
import warnings
warnings.warn("pass_fds overriding close_fds.", RuntimeWarning)
close_fds = True
if startupinfo is not None:
raise ValueError("startupinfo is only supported on Windows "
"platforms")
if creationflags != 0:
raise ValueError("creationflags is only supported on Windows "
"platforms")
assert threadpool is None
self._loop = hub.loop
# Validate the combinations of text and universal_newlines
if (text is not None and universal_newlines is not None
and bool(universal_newlines) != bool(text)):
# pylint:disable=undefined-variable
raise SubprocessError('Cannot disambiguate when both text '
'and universal_newlines are supplied but '
'different. Pass one or the other.')
self.args = args # Previously this was Py3 only.
self.stdin = None
self.stdout = None
self.stderr = None
self.pid = None
self.returncode = None
self.universal_newlines = universal_newlines
self.result = AsyncResult()
# Input and output objects. The general principle is like
# this:
#
# Parent Child
# ------ -----
# p2cwrite ---stdin---> p2cread
# c2pread <--stdout--- c2pwrite
# errread <--stderr--- errwrite
#
# On POSIX, the child objects are file descriptors. On
# Windows, these are Windows file handles. The parent objects
# are file descriptors on both platforms. The parent objects
# are -1 when not using PIPEs. The child objects are -1
# when not redirecting.
(p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
# We wrap OS handles *before* launching the child, otherwise a
# quickly terminating child could make our fds unwrappable
# (see #8458).
if mswindows:
if p2cwrite != -1:
p2cwrite = msvcrt.open_osfhandle(p2cwrite.Detach(), 0)
if c2pread != -1:
c2pread = msvcrt.open_osfhandle(c2pread.Detach(), 0)
if errread != -1:
errread = msvcrt.open_osfhandle(errread.Detach(), 0)
text_mode = PY3 and (self.encoding or self.errors or universal_newlines or text)
if text_mode or universal_newlines:
# Always a native str in universal_newlines mode, even when that
# str type is bytes. Additionally, text_mode is only true under
# Python 3, so it's actually a unicode str
self._communicate_empty_value = ''
uid, gid, gids = self.__handle_uids(user, group, extra_groups)
if p2cwrite != -1:
if PY3 and text_mode:
# Under Python 3, if we left on the 'b' we'd get different results
# depending on whether we used FileObjectPosix or FileObjectThread
self.stdin = FileObject(p2cwrite, 'w', bufsize,
encoding=self.encoding, errors=self.errors)
else:
self.stdin = FileObject(p2cwrite, 'wb', bufsize)
if c2pread != -1:
if universal_newlines or text_mode:
if PY3:
self.stdout = FileObject(c2pread, 'r', bufsize,
encoding=self.encoding, errors=self.errors)
# NOTE: Universal Newlines are broken on Windows/Py3, at least
# in some cases. This is true in the stdlib subprocess module
# as well; the following line would fix the test cases in
# test__subprocess.py that depend on python_universal_newlines,
# but would be inconsistent with the stdlib:
else:
self.stdout = FileObject(c2pread, 'rU', bufsize)
else:
self.stdout = FileObject(c2pread, 'rb', bufsize)
if errread != -1:
if universal_newlines or text_mode:
if PY3:
self.stderr = FileObject(errread, 'r', bufsize,
encoding=encoding, errors=errors)
else:
self.stderr = FileObject(errread, 'rU', bufsize)
else:
self.stderr = FileObject(errread, 'rb', bufsize)
self._closed_child_pipe_fds = False
# Convert here for the sake of all platforms. os.chdir accepts
# path-like objects natively under 3.6, but CreateProcess
# doesn't.
cwd = fsdecode(cwd) if cwd is not None else None
try:
self._execute_child(args, executable, preexec_fn, close_fds,
pass_fds, cwd, env, universal_newlines,
startupinfo, creationflags, shell,
p2cread, p2cwrite,
c2pread, c2pwrite,
errread, errwrite,
restore_signals,
gid, gids, uid, umask,
start_new_session, process_group)
except:
# Cleanup if the child failed starting.
# (gevent: New in python3, but reported as gevent bug in #347.
# Note that under Py2, any error raised below will replace the
# original error so we have to use reraise)
if not PY3:
exc_info = sys.exc_info()
for f in filter(None, (self.stdin, self.stdout, self.stderr)):
try:
f.close()
except (OSError, IOError):
pass # Ignore EBADF or other errors.
if not self._closed_child_pipe_fds:
to_close = []
if stdin == PIPE:
to_close.append(p2cread)
if stdout == PIPE:
to_close.append(c2pwrite)
if stderr == PIPE:
to_close.append(errwrite)
if hasattr(self, '_devnull'):
to_close.append(self._devnull)
for fd in to_close:
try:
os.close(fd)
except (OSError, IOError):
pass
if not PY3:
try:
reraise(*exc_info)
finally:
del exc_info
raise
def __handle_uids(self, user, group, extra_groups):
gid = None
if group is not None:
if not hasattr(os, 'setregid'):
raise ValueError("The 'group' parameter is not supported on the "
"current platform")
if isinstance(group, str):
if grp is None:
raise ValueError("The group parameter cannot be a string "
"on systems without the grp module")
gid = grp.getgrnam(group).gr_gid
elif isinstance(group, int):
gid = group
else:
raise TypeError("Group must be a string or an integer, not {}"
.format(type(group)))
if gid < 0:
raise ValueError("Group ID cannot be negative, got %s" % gid)
gids = None
if extra_groups is not None:
if not hasattr(os, 'setgroups'):
raise ValueError("The 'extra_groups' parameter is not "
"supported on the current platform")
if isinstance(extra_groups, str):
raise ValueError("Groups must be a list, not a string")
gids = []
for extra_group in extra_groups:
if isinstance(extra_group, str):
if grp is None:
raise ValueError("Items in extra_groups cannot be "
"strings on systems without the "
"grp module")
gids.append(grp.getgrnam(extra_group).gr_gid)
elif isinstance(extra_group, int):
if extra_group >= 2**64:
# This check is implicit in the C version of _Py_Gid_Converter.
#
# We actually need access to the C type ``gid_t`` to get
# its actual length. This just makes the test that was added
# for the bug pass. That's OK though, if we guess too big here,
# we should get an OverflowError from the setgroups()
# call we make. The only difference is the type of exception.
#
# See https://bugs.python.org/issue42655
raise ValueError("Item in extra_groups is too large")
gids.append(extra_group)
else:
raise TypeError("Items in extra_groups must be a string "
"or integer, not {}"
.format(type(extra_group)))
# make sure that the gids are all positive here so we can do less
# checking in the C code
for gid_check in gids:
if gid_check < 0:
raise ValueError("Group ID cannot be negative, got %s" % (gid_check,))
uid = None
if user is not None:
if not hasattr(os, 'setreuid'):
raise ValueError("The 'user' parameter is not supported on "
"the current platform")
if isinstance(user, str):
if pwd is None:
raise ValueError("The user parameter cannot be a string "
"on systems without the pwd module")
uid = pwd.getpwnam(user).pw_uid
elif isinstance(user, int):
uid = user
else:
raise TypeError("User must be a string or an integer")
if uid < 0:
raise ValueError("User ID cannot be negative, got %s" % (uid,))
return uid, gid, gids
def __repr__(self):
return '<%s at 0x%x pid=%r returncode=%r>' % (self.__class__.__name__, id(self), self.pid, self.returncode)
def _on_child(self, watcher):
watcher.stop()
status = watcher.rstatus
if os.WIFSIGNALED(status):
self.returncode = -os.WTERMSIG(status)
else:
self.returncode = os.WEXITSTATUS(status)
self.result.set(self.returncode)
def _get_devnull(self):
if not hasattr(self, '_devnull'):
self._devnull = os.open(os.devnull, os.O_RDWR)
return self._devnull
_communicating_greenlets = None
def communicate(self, input=None, timeout=None):
"""
Interact with process and return its output and error.
- Send *input* data to stdin.
- Read data from stdout and stderr, until end-of-file is reached.
- Wait for process to terminate.
The optional *input* argument should be a
string to be sent to the child process, or None, if no data