Debian Codegraph @

osrf_pycommon/process_utils/execute_process_nopty.py

raw
1 # Copyright 2014 Open Source Robotics Foundation, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 import errno
16 import os
17 import select
18
19 from subprocess import PIPE
20 from subprocess import Popen
21 from subprocess import STDOUT
22
23 import sys
24
25 _is_linux = sys.platform.lower().startswith('linux')
26 _is_windows = sys.platform.lower().startswith('win')
27
28
29 def _process_incoming_lines(incoming, left_over):
30 # This function takes the new data, the left over data from last time
31 # and returns a list of complete lines (separated by sep) as well as
32 # any sep trailing data for the next iteration
33 # This function takes and returns bytes only
34 combined = (left_over + incoming)
35 lines = combined.splitlines(True)
36 if not lines:
37 return None, left_over
38 # Use splitlines because it is magic
39 # comparing against os.linesep is not sufficient
40 if lines[-1].splitlines() != [lines[-1]]:
41 data = b''.join(lines)
42 left_over = b''
43 else:
44 data = b''.join(lines[:-1])
45 left_over = lines[-1]
46 return data, left_over
47
48
49 def _close_fds(fds_to_close):
50 # This function is used to close (if not already closed) any fds used
51 for s in fds_to_close:
52 if s is None:
53 continue
54 try:
55 os.close(s)
56 except OSError as exc:
57 # This could raise "OSError: [Errno 9] Bad file descriptor"
58 # If it has already been closed, but that's ok
59 if "Bad file descriptor" not in "{0}".format(exc):
60 raise
61
62
63 def _yield_data(p, fds, left_overs, linesep, fds_to_close=None):
64 # This function uses select and subprocess.Popen.poll to collect out
65 # from a subprocess until it has finished, yielding it as it goes
66 fds_to_close = [] if fds_to_close is None else fds_to_close
67
68 def yield_to_stream(data, stream):
69 if stream == fds[0]:
70 return data, None, None
71 else:
72 return None, data, None
73
74 try:
75 while p.poll() is None:
76 # If Windows
77 if _is_windows:
78 for stream in fds:
79 # This will not produce the best results, but at least
80 # it will function on Windows. A True IOCP implementation
81 # would be required to get streaming from Windows streams.
82 data = stream.readline()
83 if data:
84 yield yield_to_stream(data, stream)
85 continue
86 # Otherwise Unix
87 try:
88 rlist, wlist, xlist = select.select(fds, [], [])
89 except select.error as exc:
90 # Ignore EINTR
91 try:
92 errnum = exc.errno
93 except AttributeError:
94 errnum = exc[0]
95 if errnum == errno.EINTR:
96 continue
97 raise
98 for stream in rlist:
99 left_over = left_overs[stream]
100 fileno = getattr(stream, 'fileno', lambda: stream)()
101 try:
102 incoming = os.read(fileno, 1024)
103 except OSError as exc:
104 # On Linux, when using a pty, in order to get select
105 # to return when the subprocess finishes, os.close
106 # must be called on the slave pty fd after forking
107 # the subprocess with popen. On some versions of
108 # the Linux kernel this causes an Errno 5 OSError,
109 # "Input/output error". Therefore, I am explicitly
110 # catching and passing on this error. In my testing
111 # this error does not occur repeatedly (it does not
112 # become a busy wait). See:
113 # http://stackoverflow.com/a/12207447/671658
114 if _is_linux and "Input/output error" in "{0}".format(exc):
115 continue
116 raise
117 if not incoming:
118 # In this case, EOF has been reached, see docs for os.read
119 if left_over:
120 yield yield_to_stream(left_over, stream)
121 continue
122 data, left_over = _process_incoming_lines(incoming, left_over)
123 left_overs[stream] = left_over
124 yield yield_to_stream(data, stream)
125 # Done
126 yield None, None, p.returncode
127 finally:
128 # Make sure we don't leak file descriptors
129 _close_fds(fds_to_close)
130
131
132 def _execute_process_nopty(cmd, cwd, env, shell, stderr_to_stdout=True):
133 stderr = STDOUT if stderr_to_stdout else PIPE
134 with Popen(
135 cmd, stdin=PIPE, stdout=PIPE, stderr=stderr,
136 cwd=cwd, env=env, shell=shell, close_fds=False
137 ) as p:
138 # Left over data from read which isn't a complete line yet
139 left_overs = {p.stdout: b'', p.stderr: b''}
140
141 fds = list(filter(None, [p.stdout, p.stderr]))
142
143 yield from _yield_data(p, fds, left_overs, os.linesep)