Debian Codegraph @

osrf_pycommon/process_utils/async_execute_process.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 from __future__ import print_function
16
17 import sys
18
19 from .async_execute_process_asyncio import async_execute_process
20 from .async_execute_process_asyncio import get_loop
21 from .async_execute_process_asyncio import asyncio
22
23 __all__ = [
24 'async_execute_process',
25 'AsyncSubprocessProtocol',
26 'get_loop',
27 ]
28
29 async_execute_process.__doc__ = """
30 Coroutine to execute a subprocess and yield the output back asynchronously.
31
32 This function is meant to be used with the Python :py:mod:`asyncio` module,
33 which is available in Python 3.5 or greater.
34
35 Here is an example of how to use this function:
36
37 .. code-block:: python
38
39 import asyncio
40 from osrf_pycommon.process_utils import async_execute_process
41 from osrf_pycommon.process_utils import AsyncSubprocessProtocol
42 from osrf_pycommon.process_utils import get_loop
43
44
45 async def setup():
46 transport, protocol = await async_execute_process(
47 AsyncSubprocessProtocol, ['ls', '/usr'])
48 returncode = await protocol.complete
49 return returncode
50
51 retcode = get_loop().run_until_complete(setup())
52 get_loop().close()
53
54 Tthe first argument is the default
55 :py:class:`AsyncSubprocessProtocol` protocol class, which simply prints output
56 from stdout to stdout and output from stderr to stderr.
57
58 If you want to capture and do something with the output or write to the stdin,
59 then you need to subclass from the :py:class:`AsyncSubprocessProtocol` class,
60 and override the ``on_stdout_received``, ``on_stderr_received``, and
61 ``on_process_exited`` functions.
62
63 See the documentation for the :py:class:`AsyncSubprocessProtocol` class for
64 more details, but here is an example which uses asyncio from Python 3.5:
65
66 .. code-block:: python
67
68 import asyncio
69 from osrf_pycommon.process_utils import async_execute_process
70 from osrf_pycommon.process_utils import AsyncSubprocessProtocol
71 from osrf_pycommon.process_utils import get_loop
72
73
74 class MyProtocol(AsyncSubprocessProtocol):
75 def __init__(self, file_name, **kwargs):
76 self.fh = open(file_name, 'w')
77 AsyncSubprocessProtocol.__init__(self, **kwargs)
78
79 def on_stdout_received(self, data):
80 # Data has line endings intact, but is bytes in Python 3
81 self.fh.write(data.decode('utf-8'))
82
83 def on_stderr_received(self, data):
84 self.fh.write(data.decode('utf-8'))
85
86 def on_process_exited(self, returncode):
87 self.fh.write("Exited with return code: {0}".format(returncode))
88 self.fh.close()
89
90
91 async def log_command_to_file(cmd, file_name):
92
93 def create_protocol(**kwargs):
94 return MyProtocol(file_name, **kwargs)
95
96 transport, protocol = await async_execute_process(
97 create_protocol, cmd)
98 returncode = await protocol.complete
99 return returncode
100
101 get_loop().run_until_complete(
102 log_command_to_file(['ls', '/'], '/tmp/out.txt'))
103 get_loop().close()
104
105 See the :py:class:`subprocess.Popen` class for more details on some of the
106 parameters to this function like ``cwd``, ``env``, and ``shell``.
107
108 See the :py:func:`osrf_pycommon.process_utils.execute_process` function for
109 more details on the ``emulate_tty`` parameter.
110
111 :param protocol_class: Protocol class which handles subprocess callbacks
112 :type protocol_class: :py:class:`AsyncSubprocessProtocol` or a subclass
113 :param list cmd: list of arguments where the executable is the first item
114 :param str cwd: directory in which to run the command
115 :param dict env: a dictionary of environment variable names to values
116 :param bool shell: if True, the ``cmd`` variable is interpreted by a the shell
117 :param bool emulate_tty: if True, pty's are passed to the subprocess for stdout
118 and stderr, see :py:func:`osrf_pycommon.process_utils.execute_process`.
119 :param bool stderr_to_stdout: if True, stderr is directed to stdout, so they
120 are not captured separately.
121 """
122
123
124 class AsyncSubprocessProtocol(asyncio.SubprocessProtocol):
125 """
126 Protocol to subclass to get events from :py:func:`async_execute_process`.
127
128 When subclassing this Protocol class, you should override these functions:
129
130 .. code-block:: python
131
132 def on_stdout_received(self, data):
133 # ...
134
135 def on_stderr_received(self, data):
136 # ...
137
138 def on_process_exited(self, returncode):
139 # ...
140
141
142 By default these functions just print the data received from
143 stdout and stderr and does nothing when the process exits.
144
145 Data received by the ``on_stdout_received`` and ``on_stderr_received``
146 functions is always in ``bytes``.
147 Therefore, it may be necessary to call ``.decode()`` on the data before
148 printing to the screen.
149
150 Additionally, the data received will not be stripped of new lines, so take
151 that into consideration when printing the result.
152
153 You can also override these less commonly used functions:
154
155 .. code-block:: python
156
157 def on_stdout_open(self):
158 # ...
159
160 def on_stdout_close(self, exc):
161 # ...
162
163 def on_stderr_open(self):
164 # ...
165
166 def on_stderr_close(self, exc):
167 # ...
168
169
170 These functions are called when stdout/stderr are opened and closed, and
171 can be useful when using pty's for example. The ``exc`` parameter of the
172 ``*_close`` functions is None unless there was an exception.
173
174 In addition to the overridable functions this class has a few useful
175 public attributes.
176 The ``stdin`` attribute is a reference to the PipeProto which follows the
177 :py:class:`asyncio.WriteTransport` interface.
178 The ``stdout`` and ``stderr`` attributes also reference their PipeProto.
179 The ``complete`` attribute is a :py:class:`asyncio.Future` which is set to
180 complete when the process exits and its result is the return code.
181
182 The ``complete`` attribute can be used like this:
183
184 .. code-block:: python
185
186 import asyncio
187 from osrf_pycommon.process_utils import async_execute_process
188 from osrf_pycommon.process_utils import AsyncSubprocessProtocol
189 from osrf_pycommon.process_utils import get_loop
190
191
192 async def setup():
193 transport, protocol = await async_execute_process(
194 AsyncSubprocessProtocol, ['ls', '-G', '/usr'])
195 retcode = await protocol.complete
196 print("Exited with", retcode)
197
198 # This will block until the protocol.complete Future is done.
199 get_loop().run_until_complete(setup())
200 get_loop().close()
201
202 """
203 def __init__(self, stdin=None, stdout=None, stderr=None):
204 self.stdin = stdin
205 self.stdout = stdout
206 self.stderr = stderr
207 self.complete = asyncio.Future()
208 asyncio.SubprocessProtocol.__init__(self)
209
210 def connection_made(self, transport):
211 self.transport = transport
212 if self.stdin is None:
213 self.stdin = self.transport.get_pipe_transport(0)
214 if self.stdout is None:
215 self.stdout = self.transport.get_pipe_transport(1)
216 if self.stderr is None:
217 self.stderr = self.transport.get_pipe_transport(2)
218
219 def pipe_data_received(self, fd, data):
220 # This function is only called when pty's are not being used
221 stdout = self.stdout
222 if not isinstance(stdout, int):
223 stdout = 1
224 if fd == stdout:
225 if hasattr(self, 'on_stdout_received'):
226 self.on_stdout_received(data)
227 else:
228 assert fd == 2
229 if hasattr(self, 'on_stderr_received'):
230 self.on_stderr_received(data)
231
232 def _on_stdout_received(self, data):
233 # print(data.__repr__())
234 print(data.decode(), end='')
235
236 def _on_stderr_received(self, data):
237 # print(data.__repr__(), file=sys.stderr)
238 print(data.decode(), end='', file=sys.stderr)
239
240 def process_exited(self):
241 retcode = self.transport.get_returncode()
242 self.complete.set_result(retcode)
243 self.on_process_exited(retcode)
244
245 def on_process_exited(self, returncode):
246 # print("Exited with", returncode)
247 pass
248
249
250 get_loop.__doc__ = """\
251 This function will return the proper event loop for the subprocess async calls.
252
253 On Unix this just returns :py:func:`asyncio.get_event_loop`, but on Windows it
254 will set and return a :py:class:`asyncio.ProactorEventLoop` instead.
255 """