Skip to content

Commit 93bf61d

Browse files
author
astrand
committed
Optimization for communicate(): If only one of stdin/stdout/stderr is
redirected, using select() or threads is unnecessary. git-svn-id: http://svn.python.org/projects/python/trunk@38556 6015fed2-1504-0410-9fe1-9d1591cc4771
1 parent 1a6301e commit 93bf61d

1 file changed

Lines changed: 29 additions & 16 deletions

File tree

Lib/subprocess.py

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -619,6 +619,33 @@ def _translate_newlines(self, data):
619619
data = data.replace("\r", "\n")
620620
return data
621621

622+
def communicate(self, input=None):
623+
"""Interact with process: Send data to stdin. Read data from
624+
stdout and stderr, until end-of-file is reached. Wait for
625+
process to terminate. The optional input argument should be a
626+
string to be sent to the child process, or None, if no data
627+
should be sent to the child.
628+
629+
communicate() returns a tuple (stdout, stderr)."""
630+
631+
# Optimization: If we are only using one pipe, or no pipe at
632+
# all, using select() or threads is unnecessary.
633+
if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
634+
stdout = None
635+
stderr = None
636+
if self.stdin:
637+
if input:
638+
self.stdin.write(input)
639+
self.stdin.close()
640+
elif self.stdout:
641+
stdout = self.stdout.read()
642+
elif self.stderr:
643+
stderr = self.stderr.read()
644+
self.wait()
645+
return (stdout, stderr)
646+
647+
return self._communicate(input)
648+
622649

623650
if mswindows:
624651
#
@@ -811,14 +838,7 @@ def _readerthread(self, fh, buffer):
811838
buffer.append(fh.read())
812839

813840

814-
def communicate(self, input=None):
815-
"""Interact with process: Send data to stdin. Read data from
816-
stdout and stderr, until end-of-file is reached. Wait for
817-
process to terminate. The optional input argument should be a
818-
string to be sent to the child process, or None, if no data
819-
should be sent to the child.
820-
821-
communicate() returns a tuple (stdout, stderr)."""
841+
def _communicate(self, input):
822842
stdout = None # Return
823843
stderr = None # Return
824844

@@ -1066,14 +1086,7 @@ def wait(self):
10661086
return self.returncode
10671087

10681088

1069-
def communicate(self, input=None):
1070-
"""Interact with process: Send data to stdin. Read data from
1071-
stdout and stderr, until end-of-file is reached. Wait for
1072-
process to terminate. The optional input argument should be a
1073-
string to be sent to the child process, or None, if no data
1074-
should be sent to the child.
1075-
1076-
communicate() returns a tuple (stdout, stderr)."""
1089+
def _communicate(self, input):
10771090
read_set = []
10781091
write_set = []
10791092
stdout = None # Return

0 commit comments

Comments
 (0)