| 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 os |
| 16 |
import sys |
| 17 |
|
| 18 |
from .execute_process_nopty import _execute_process_nopty |
| 19 |
try: |
| 20 |
from .execute_process_pty import _execute_process_pty |
| 21 |
except ImportError: |
| 22 |
# pty doesn't work on Windows, it will fail to import |
| 23 |
# so fallback to non pty implementation |
| 24 |
_execute_process_pty = None |
| 25 |
|
| 26 |
|
| 27 |
def execute_process(cmd, cwd=None, env=None, shell=False, emulate_tty=False): |
| 28 |
"""Executes a command with arguments and returns output line by line. |
| 29 |
|
| 30 |
All arguments, except ``emulate_tty``, are passed directly to |
| 31 |
:py:class:`subprocess.Popen`. |
| 32 |
|
| 33 |
``execute_process`` returns a generator which yields the output, line by |
| 34 |
line, until the subprocess finishes at which point the return code |
| 35 |
is yielded. |
| 36 |
|
| 37 |
This is an example of how this function should be used: |
| 38 |
|
| 39 |
.. code-block:: python |
| 40 |
|
| 41 |
from __future__ import print_function |
| 42 |
from osrf_pycommon.process_utils import execute_process |
| 43 |
|
| 44 |
cmd = ['ls', '-G'] |
| 45 |
for line in execute_process(cmd, cwd='/usr'): |
| 46 |
if isinstance(line, int): |
| 47 |
# This is a return code, the command has exited |
| 48 |
print("'{0}' exited with: {1}".format(' '.join(cmd), line)) |
| 49 |
continue # break would also be appropriate here |
| 50 |
# In Python 3, it will be a bytes array which needs to be decoded |
| 51 |
if not isinstance(line, str): |
| 52 |
line = line.decode('utf-8') |
| 53 |
# Then print it to the screen |
| 54 |
print(line, end='') |
| 55 |
|
| 56 |
``stdout`` and ``stderr`` are always captured together and returned line |
| 57 |
by line through the returned generator. |
| 58 |
New line characters are preserved in the output, so if re-printing the data |
| 59 |
take care to use ``end=''`` or first ``rstrip`` the output lines. |
| 60 |
|
| 61 |
When ``emulate_tty`` is used on Unix systems, commands will identify that |
| 62 |
they are on a tty and should output color to the screen as if you were |
| 63 |
running it on the terminal, and therefore there should not be any need to |
| 64 |
pass arguments like ``-c color.ui=always`` to commands like ``git``. |
| 65 |
Additionally, programs might also behave differently in when |
| 66 |
``emulate_tty`` is being used, for example, Python will default to |
| 67 |
unbuffered output when it detects a tty. |
| 68 |
|
| 69 |
``emulate_tty`` works by using psuedo-terminals on Unix machines, and so |
| 70 |
if you are running this command many times in parallel (like hundreds |
| 71 |
of times) then you may get one of a few different :py:exc:`OSError`'s. |
| 72 |
For example, "OSError: [Errno 24] Too many open files: '/dev/ttyp0'" or |
| 73 |
"OSError: out of pty devices". |
| 74 |
You should also be aware that you share pty devices with the rest of the |
| 75 |
system, so even if you are not using a lot, it is possible to get |
| 76 |
this error. |
| 77 |
You can catch this error before getting data from the generator, so when |
| 78 |
using ``emulate_tty`` you might want to do something like this: |
| 79 |
|
| 80 |
.. code-block:: python |
| 81 |
|
| 82 |
from __future__ import print_function |
| 83 |
from osrf_pycommon.process_utils import execute_process |
| 84 |
|
| 85 |
cmd = ['ls', '-G', '/usr'] |
| 86 |
try: |
| 87 |
output = execute_process(cmd, emulate_tty=True) |
| 88 |
except OSError: |
| 89 |
output = execute_process(cmd, emulate_tty=False) |
| 90 |
for line in output: |
| 91 |
if isinstance(line, int): |
| 92 |
print("'{0}' exited with: {1}".format(' '.join(cmd), line)) |
| 93 |
continue |
| 94 |
# In Python 3, it will be a bytes array which needs to be decoded |
| 95 |
if not isinstance(line, str): |
| 96 |
line = line.decode('utf-8') |
| 97 |
print(line, end='') |
| 98 |
|
| 99 |
This way if a pty cannot be opened in order to emulate the tty then you |
| 100 |
can try again without emulation, and any other :py:exc:`OSError` should |
| 101 |
raise again with ``emulate_tty`` set to ``False``. |
| 102 |
Obviously, you only want to do this if emulating the tty is non-critical |
| 103 |
to your processing, like when you are using it to capture color. |
| 104 |
|
| 105 |
Any color information that the command outputs as ANSI escape sequences |
| 106 |
is captured by this command. |
| 107 |
That way you can print the output to the screen and preserve the color |
| 108 |
formatting. |
| 109 |
|
| 110 |
If you do not want color to be in the output, then try setting |
| 111 |
``emulate_tty`` to ``False``, but that does not guarantee that there is no |
| 112 |
color in the output, instead it only will cause called processes to |
| 113 |
identify that they are not being run in a terminal. |
| 114 |
Most well behaved programs will not output color if they detect that |
| 115 |
they are not being executed in a terminal, but you shouldn't rely on that. |
| 116 |
|
| 117 |
If you want to ensure there is no color in the output from an executed |
| 118 |
process, then use this function: |
| 119 |
|
| 120 |
:py:func:`osrf_pycommon.terminal_color.remove_ansi_escape_sequences` |
| 121 |
|
| 122 |
Exceptions can be raised by functions called by the implementation, |
| 123 |
for example, :py:class:`subprocess.Popen` can raise an :py:exc:`OSError` |
| 124 |
when the given command is not found. |
| 125 |
If you want to check for the existence of an executable on the path, |
| 126 |
see: :py:func:`which`. |
| 127 |
However, this function itself does not raise any special exceptions. |
| 128 |
|
| 129 |
:param list cmd: list of strings with the first item being a command |
| 130 |
and subsequent items being any arguments to that command; |
| 131 |
passed directly to :py:class:`subprocess.Popen`. |
| 132 |
:param str cwd: path in which to run the command, defaults to None which |
| 133 |
means :py:func:`os.getcwd` is used; |
| 134 |
passed directly to :py:class:`subprocess.Popen`. |
| 135 |
:param dict env: environment dictionary to use for executing the command, |
| 136 |
default is None which uses the :py:obj:`os.environ` environment; |
| 137 |
passed directly to :py:class:`subprocess.Popen`. |
| 138 |
:param bool shell: If True the system shell is used to evaluate the |
| 139 |
command, default is False; |
| 140 |
passed directly to :py:class:`subprocess.Popen`. |
| 141 |
:param bool emulate_tty: If True attempts to use a pty to convince |
| 142 |
subprocess's that they are being run in a terminal. Typically this is |
| 143 |
useful for capturing colorized output from commands. This does not |
| 144 |
work on Windows (no pty's), so it is considered False even when True. |
| 145 |
Defaults to False. |
| 146 |
:returns: a generator which yields output from the command line by line |
| 147 |
:rtype: generator which yields strings |
| 148 |
""" |
| 149 |
exp_func = _execute_process_nopty |
| 150 |
if emulate_tty and _execute_process_pty is not None: |
| 151 |
exp_func = _execute_process_pty |
| 152 |
for out, err, ret in exp_func(cmd, cwd, env, shell, stderr_to_stdout=True): |
| 153 |
if ret is None: |
| 154 |
yield out |
| 155 |
continue |
| 156 |
yield ret |
| 157 |
|
| 158 |
|
| 159 |
def execute_process_split( |
| 160 |
cmd, cwd=None, env=None, shell=False, emulate_tty=False |
| 161 |
): |
| 162 |
""":py:func:`execute_process`, except ``stderr`` is returned separately. |
| 163 |
|
| 164 |
Instead of yielding output line by line until yielding a return code, this |
| 165 |
function always a triplet of ``stdout``, ``stderr``, and return code. |
| 166 |
Each time only one of the three will not be None. |
| 167 |
Once you receive a non-None return code (type will be int) there will be no |
| 168 |
more ``stdout`` or ``stderr``. |
| 169 |
Therefore you can use the command like this: |
| 170 |
|
| 171 |
.. code-block:: python |
| 172 |
|
| 173 |
from __future__ import print_function |
| 174 |
import sys |
| 175 |
from osrf_pycommon.process_utils import execute_process_split |
| 176 |
|
| 177 |
cmd = ['time', 'ls', '-G'] |
| 178 |
for out, err, ret in execute_process_split(cmd, cwd='/usr'): |
| 179 |
# In Python 3, it will be a bytes array which needs to be decoded |
| 180 |
out = out.decode('utf-8') if out is not None else None |
| 181 |
err = err.decode('utf-8') if err is not None else None |
| 182 |
if ret is not None: |
| 183 |
# This is a return code, the command has exited |
| 184 |
print("'{0}' exited with: {1}".format(' '.join(cmd), ret)) |
| 185 |
break |
| 186 |
if out is not None: |
| 187 |
print(out, end='') |
| 188 |
if err is not None: |
| 189 |
print(err, end='', file=sys.stderr) |
| 190 |
|
| 191 |
When using this, it is possible that the ``stdout`` and ``stderr`` data can |
| 192 |
be returned in a different order than what would happen on the terminal. |
| 193 |
This is due to the fact that the subprocess is given different buffers for |
| 194 |
``stdout`` and ``stderr`` and so there is a race condition on the |
| 195 |
subprocess writing to the different buffers and this command reading the |
| 196 |
buffers. |
| 197 |
This can be avoided in most scenarios by using ``emulate_tty``, because of |
| 198 |
the use of ``pty``'s, though the ordering can still not be guaranteed and |
| 199 |
the number of ``pty``'s is finite as explained in the documentation for |
| 200 |
:py:func:`execute_process`. |
| 201 |
For situations where output ordering between ``stdout`` and ``stderr`` are |
| 202 |
critical, they should not be returned separately and instead should share |
| 203 |
one buffer, and so :py:func:`execute_process` should be used. |
| 204 |
|
| 205 |
For all other parameters and documentation see: :py:func:`execute_process` |
| 206 |
""" |
| 207 |
exp_func = _execute_process_nopty |
| 208 |
if emulate_tty and _execute_process_pty is not None: |
| 209 |
exp_func = _execute_process_pty |
| 210 |
return exp_func(cmd, cwd, env, shell, stderr_to_stdout=False) |
| 211 |
|
| 212 |
|
| 213 |
try: |
| 214 |
from shutil import which as _which |
| 215 |
except ImportError: |
| 216 |
_which = None |
| 217 |
|
| 218 |
|
| 219 |
def _which_backport(cmd, mode=os.F_OK | os.X_OK, path=None): |
| 220 |
# Check that a given file can be accessed with the correct mode. |
| 221 |
# Additionally check that `file` is not a directory, as on Windows |
| 222 |
# directories pass the os.access check. |
| 223 |
def _access_check(fn, mode): |
| 224 |
return (os.path.exists(fn) and os.access(fn, mode) and not |
| 225 |
os.path.isdir(fn)) |
| 226 |
|
| 227 |
# If we're given a path with a directory part, look it up directly rather |
| 228 |
# than referring to PATH directories. This includes checking relative |
| 229 |
# to the current directory, e.g. ./script |
| 230 |
if os.path.dirname(cmd): |
| 231 |
if _access_check(cmd, mode): |
| 232 |
return cmd |
| 233 |
return None |
| 234 |
|
| 235 |
if path is None: |
| 236 |
path = os.environ.get("PATH", os.defpath) |
| 237 |
if not path: |
| 238 |
return None |
| 239 |
path = path.split(os.pathsep) |
| 240 |
|
| 241 |
if sys.platform == "win32": |
| 242 |
# The current directory takes precedence on Windows. |
| 243 |
if os.curdir not in path: |
| 244 |
path.insert(0, os.curdir) |
| 245 |
|
| 246 |
# PATHEXT is necessary to check on Windows. |
| 247 |
pathext = os.environ.get("PATHEXT", "").split(os.pathsep) |
| 248 |
# See if the given file matches any of the expected path extensions. |
| 249 |
# This will allow us to short circuit when given "python.exe". |
| 250 |
# If it does match, only test that one, otherwise we have to try |
| 251 |
# others. |
| 252 |
if any(cmd.lower().endswith(ext.lower()) for ext in pathext): |
| 253 |
files = [cmd] |
| 254 |
else: |
| 255 |
files = [cmd + ext for ext in pathext] |
| 256 |
else: |
| 257 |
# On other platforms you don't have things like PATHEXT to tell you |
| 258 |
# what file suffixes are executable, so just pass on cmd as-is. |
| 259 |
files = [cmd] |
| 260 |
|
| 261 |
seen = set() |
| 262 |
for directory in path: |
| 263 |
normdir = os.path.normcase(directory) |
| 264 |
if normdir not in seen: |
| 265 |
seen.add(normdir) |
| 266 |
for thefile in files: |
| 267 |
name = os.path.join(directory, thefile) |
| 268 |
if _access_check(name, mode): |
| 269 |
return name |
| 270 |
return None |
| 271 |
|
| 272 |
|
| 273 |
def which(cmd, mode=os.F_OK | os.X_OK, path=None, **kwargs): |
| 274 |
"""Given a command, mode, and a PATH string, return the path which |
| 275 |
conforms to the given mode on the PATH, or None if there is no such |
| 276 |
file. |
| 277 |
|
| 278 |
`mode` defaults to ``os.F_OK | os.X_OK``. `path` defaults to the result |
| 279 |
of ``os.environ.get("PATH")``, or can be overridden with a custom search |
| 280 |
path. |
| 281 |
|
| 282 |
Backported from :py:func:`shutil.which` |
| 283 |
(`<https://docs.python.org/3.3/library/shutil.html#shutil.which>`_), |
| 284 |
available in Python 3.3. |
| 285 |
""" |
| 286 |
kwargs.update({'mode': mode, 'path': path}) |
| 287 |
global _which |
| 288 |
if _which is not None: |
| 289 |
return _which(cmd, **kwargs) |
| 290 |
return _which_backport(cmd, **kwargs) |