pax_global_header00006660000000000000000000000064133435012730014513gustar00rootroot0000000000000052 comment=7c33f69c5424ea3a46ccbc74476fabbec5044808 python-sh-1.12.14/000077500000000000000000000000001334350127300136125ustar00rootroot00000000000000python-sh-1.12.14/CHANGELOG.md000066400000000000000000000314151334350127300154270ustar00rootroot00000000000000# Changelog ## 1.12.14 - 6/6/17 * bugfix for poor sleep performance [#378](https://github.com/amoffat/sh/issues/378) * allow passing raw integer file descriptors for `_out` and `_err` handlers * bugfix for when `_tee` and `_out` are used, and the `_out` is a tty or pipe [#384](https://github.com/amoffat/sh/issues/384) * bugfix where python 3.3+ detected different arg counts for bound method output callbacks [#380](https://github.com/amoffat/sh/issues/380) ## 1.12.12, 1.12.13 - 3/30/17 * pypi readme doc bugfix [PR#377](https://github.com/amoffat/sh/pull/377) ## 1.12.11 - 3/13/17 * bugfix for relative paths to `sh.Command` not expanding to absolute paths [#372](https://github.com/amoffat/sh/issues/372) * updated for python 3.6 * bugfix for SIGPIPE not being handled correctly on pipelined processes [#373](https://github.com/amoffat/sh/issues/373) ## 1.12.10 - 3/02/17 * bugfix for file descriptors over 1024 [#356](https://github.com/amoffat/sh/issues/356) * bugfix when `_err_to_out` is True and `_out` is pipe or tty [#365](https://github.com/amoffat/sh/issues/365) ## 1.12.9 - 1/04/17 * added `_bg_exc` for silencing exceptions in background threads [#350](https://github.com/amoffat/sh/pull/350) ## 1.12.8 - 12/16/16 * bugfix for patched glob.glob on python3.5 [#341](https://github.com/amoffat/sh/issues/341) ## 1.12.7 - 12/07/16 * added `_out` and `_out_bufsize` validator [#346](https://github.com/amoffat/sh/issues/346) * bugfix for internal stdout thread running when it shouldn't [#346](https://github.com/amoffat/sh/issues/346) ## 1.12.6 - 12/02/16 * regression bugfix on timeout [#344](https://github.com/amoffat/sh/issues/344) * regression bugfix on `_ok_code=None` ## 1.12.5 - 12/01/16 * further improvements on cpu usage ## 1.12.4 - 11/30/16 * regression in cpu usage [#339](https://github.com/amoffat/sh/issues/339) ## 1.12.3 - 11/29/16 * fd leak regression and fix for flawed fd leak detection test [#337](https://github.com/amoffat/sh/pull/337) ## 1.12.2 - 11/28/16 * support for `io.StringIO` in python2 ## 1.12.1 - 11/28/16 * added support for using raw file descriptors for `_in`, `_out`, and `_err` * removed `.close()`ing `_out` handler if FIFO detected ## 1.12.0 - 11/21/16 * composed commands no longer propagate `_bg` * better support for using `sys.stdin` and `sys.stdout` for `_in` and `_out` * bugfix where `which()` would not stop searching at the first valid executable found in PATH * added `_long_prefix` for programs whose long arguments start with something other than `--` [#278](https://github.com/amoffat/sh/pull/278) * added `_log_msg` for advanced configuration of log message [#311](https://github.com/amoffat/sh/pull/311) * added `sh.contrib.sudo` * added `_arg_preprocess` for advanced command wrapping * alter callable `_in` arguments to signify completion with falsy chunk * bugfix where pipes passed into `_out` or `_err` were not flushed on process end [#252](https://github.com/amoffat/sh/pull/252) * deprecated `with sh.args(**kwargs)` in favor of `sh2 = sh(**kwargs)` * made `sh.pushd` thread safe * added `.kill_group()` and `.signal_group()` methods for better process control [#237](https://github.com/amoffat/sh/pull/237) * added `new_session` special keyword argument for controlling spawned process session [#266](https://github.com/amoffat/sh/issues/266) * bugfix better handling for EINTR on system calls [#292](https://github.com/amoffat/sh/pull/292) * bugfix where with-contexts were not threadsafe [#247](https://github.com/amoffat/sh/issues/195) * `_uid` new special keyword param for specifying the user id of the process [#133](https://github.com/amoffat/sh/issues/133) * bugfix where exceptions were swallowed by processes that weren't waited on [#309](https://github.com/amoffat/sh/issues/309) * bugfix where processes that dupd their stdout/stderr to a long running child process would cause sh to hang [#310](https://github.com/amoffat/sh/issues/310) * improved logging output [#323](https://github.com/amoffat/sh/issues/323) * bugfix for python3+ where binary data was passed into a process's stdin [#325](https://github.com/amoffat/sh/issues/325) * Introduced execution contexts which allow baking of common special keyword arguments into all commands [#269](https://github.com/amoffat/sh/issues/269) * `Command` and `which` now can take an optional `paths` parameter which specifies the search paths [#226](https://github.com/amoffat/sh/issues/226) * `_preexec_fn` option for executing a function after the child process forks but before it execs [#260](https://github.com/amoffat/sh/issues/260) * `_fg` reintroduced, with limited functionality. hurrah! [#92](https://github.com/amoffat/sh/issues/92) * bugfix where a command would block if passed a fd for stdin that wasn't yet ready to read [#253](https://github.com/amoffat/sh/issues/253) * `_long_sep` can now take `None` which splits the long form arguments into individual arguments [#258](https://github.com/amoffat/sh/issues/258) * making `_piped` perform "direct" piping by default (linking fds together). this fixes memory problems [#270](https://github.com/amoffat/sh/issues/270) * bugfix where calling `next()` on an iterable process that has raised `StopIteration`, hangs [#273](https://github.com/amoffat/sh/issues/273) * `sh.cd` called with no arguments no changes into the user's home directory, like native `cd` [#275](https://github.com/amoffat/sh/issues/275) * `sh.glob` removed entirely. the rationale is correctness over hand-holding. [#279](https://github.com/amoffat/sh/issues/279) * added `_truncate_exc`, defaulting to `True`, which tells our exceptions to truncate output. * bugfix for exceptions whose messages contained unicode * `_done` callback no longer assumes you want your command put in the background. * `_done` callback is now called asynchronously in a separate thread. * `_done` callback is called regardless of exception, which is necessary in order to release held resources, for example a process pool ## 1.10 - 12/30/14 * partially applied functions with `functools.partial` have been fixed for `_out` and `_err` callbacks [#160](https://github.com/amoffat/sh/issues/160) * `_out` or `_err` being callables no longer puts the running command in the background. to achieve the previous behavior, pass `_bg=True` to your command. * deprecated `_with` contexts [#195](https://github.com/amoffat/sh/issues/195) * `_timeout_signal` allows you to specify your own signal to kill a timed-out process with. use a constant from the `signal` stdlib module. [#171](https://github.com/amoffat/sh/issues/171) * signal exceptions can now be caught by number or name. `SignalException_9 == SignalException_SIGKILL` * child processes that timeout via `_timeout` raise `sh.TimeoutException` instead of `sh.SignalExeception_9` [#172](https://github.com/amoffat/sh/issues/172) * fixed `help(sh)` from the python shell and `pydoc sh` from the command line. [#173](https://github.com/amoffat/sh/issues/173) * program names can no longer be shadowed by names that sh.py defines internally. removed the requirement of trailing underscores for programs that could have their names shadowed, like `id`. * memory optimization when a child process's stdin is a newline-delimted string and our bufsize is newlines * feature, `_done` special keyword argument that accepts a callback to be called when the command completes successfully [#185](https://github.com/amoffat/sh/issues/185) * bugfix for being unable to print a baked command in python3+ [#176](https://github.com/amoffat/sh/issues/176) * bugfix for cwd not existing and causing the child process to continue running parent process code [#202](https://github.com/amoffat/sh/issues/202) * child process is now guaranteed to exit on exception between fork and exec. * fix python2 deprecation warning when running with -3 [PR #165](https://github.com/amoffat/sh/pull/165) * bugfix where sh.py was attempting to execute directories [#196](https://github.com/amoffat/sh/issues/196), [PR #189](https://github.com/amoffat/sh/pull/189) * only backgrounded processes will ignore SIGHUP * allowed `ok_code` to take a `range` object. [#PR 210](https://github.com/amoffat/sh/pull/210/files) * added `sh.args` with context which allows overriding of all command defaults for the duration of that context. * added `sh.pushd` with context which takes a directory name and changes to that directory for the duration of that with context. [PR #206](https://github.com/amoffat/sh/pull/206) * tests now include python 3.4 if available. tests also stop on the first python that suite that fails. * SIGABRT, SIGBUS, SIGFPE, SIGILL, SIGPIPE, SIGSYS have been added to the list of signals that throw an exception [PR #201](https://github.com/amoffat/sh/pull/201) * "callable" builtin has been faked for python3.1, which lacks it. * "direct" option added to `_piped` special keyword argument, which allows sh to hand off a process's stdout fd directly to another process, instead of buffering its stdout internally, then handing it off. [#119](https://github.com/amoffat/sh/issues/119) ## 1.09 - 9/08/13 * Fixed encoding errors related to a system encoding "ascii". [#123](https://github.com/amoffat/sh/issues/123) * Added exit_code attribute to SignalException and ErrorReturnCode exception classes. [#127](https://github.com/amoffat/sh/issues/127) * Making the default behavior of spawned processes to not be explicitly killed when the parent python process ends. Also making the spawned process ignore SIGHUP. [#139](https://github.com/amoffat/sh/issues/139) * Made OSX sleep hack to apply to PY2 as well as PY3. ## 1.08 - 1/29/12 * Added SignalException class and made all commands that end terminate by a signal defined in SIGNALS_THAT_SHOULD_THROW_EXCEPTION raise it. [#91](https://github.com/amoffat/sh/issues/91) * Bugfix where CommandNotFound was not being raised if Command was created by instantiation. [#113](https://github.com/amoffat/sh/issues/113) * Bugfix for Commands that are wrapped with functools.wraps() [#121](https://github.com/amoffat/sh/issues/121] * Bugfix where input arguments were being assumed as ascii or unicode, but never as a string in a different encoding. * _long_sep keyword argument added joining together a dictionary of arguments passed in to a command * Commands can now be passed a dictionary of args, and the keys will be interpretted "raw", with no underscore-to-hyphen conversion * Reserved Python keywords can now be used as subcommands by appending an underscore `_` to them ## 1.07 - 11/21/12 * Bugfix for PyDev when `locale.getpreferredencoding()` is empty. * Fixes for IPython3 that involve `sh.` and `sh?` * Added `_tee` special keyword argument to force stdout/stderr to store internally and make available for piping data that is being redirected. * Added `_decode_errors` to be passed to all stdout/stderr decoding of a process. * Added `_no_out`, `_no_err`, and `_no_pipe` special keyword arguments. These are used for long-running processes with lots of output. * Changed custom loggers that were created for each process to fixed loggers, so there are no longer logger references laying around in the logging module after the process ends and it garbage collected. ## 1.06 - 11/10/12 * Removed old undocumented cruft of ARG1..ARGN and ARGV. * Bugfix where `logging_enabled` could not be set from the importing module. * Disabled garbage collection before fork to prevent garbage collection in child process. * Major bugfix where cyclical references were preventing process objects (and their associated stdout/stderr buffers) from being garbage collected. * Bugfix in RunningCommand and OProc loggers, which could get really huge if a command was called that had a large number of arguments. ## 1.05 - 10/20/12 * Changing status from alpha to beta. * Python 3.3 officially supported. * Documentation fix. The section on exceptions now references the fact that signals do not raise an exception, even for signals that might seem like they should, e.g. segfault. * Bugfix with Python 3.3 where importing commands from the sh namespace resulted in an error related to `__path__` * Long-form and short-form options to commands may now be given False to disable the option from being passed into the command. This is useful to pass in a boolean flag that you flip to either True or False to enable or disable some functionality at runtime. ## 1.04 - 10/07/12 * Making `Command` class resolve the `path` parameter with `which` by default instead of expecting it to be resolved before it is passed in. This change shouldn't affect backwards compatibility. * Fixing a bug when an exception is raised from a program, and the error output has non-ascii text. This didn't work in Python < 3.0, because .decode()'s default encoding is typically ascii. python-sh-1.12.14/LICENSE.txt000066400000000000000000000020511334350127300154330ustar00rootroot00000000000000Copyright (C) 2011-2012 by Andrew Moffat Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. python-sh-1.12.14/MANIFEST.in000066400000000000000000000001121334350127300153420ustar00rootroot00000000000000include CHANGELOG.md LICENSE.txt README.rst test.py global-exclude *.pyc python-sh-1.12.14/PKG-INFO000066400000000000000000000077161334350127300147220ustar00rootroot00000000000000Metadata-Version: 1.1 Name: sh Version: 1.12.14 Summary: Python subprocess replacement Home-page: https://github.com/amoffat/sh Author: Andrew Moffat Author-email: andrew.robert.moffat@gmail.com License: MIT Description: .. image:: https://raw.githubusercontent.com/amoffat/sh/master/logo-230.png :target: https://amoffat.github.com/sh :alt: Logo | .. image:: https://img.shields.io/pypi/v/sh.svg?style=flat-square :target: https://pypi.python.org/pypi/sh :alt: Version .. image:: https://img.shields.io/pypi/pyversions/sh.svg?style=flat-square :target: https://pypi.python.org/pypi/sh :alt: Python Versions .. image:: https://img.shields.io/travis/amoffat/sh/master.svg?style=flat-square :target: https://travis-ci.org/amoffat/sh :alt: Build Status .. image:: https://img.shields.io/coveralls/amoffat/sh.svg?style=flat-square :target: https://coveralls.io/r/amoffat/sh?branch=master :alt: Coverage Status | sh is a full-fledged subprocess replacement for Python 2.6 - 3.6, PyPy and PyPy3 that allows you to call any program as if it were a function: .. code:: python from sh import ifconfig print ifconfig("eth0") sh is *not* a collection of system commands implemented in Python. `Complete documentation here`_ Installation ============ :: $> pip install sh Updating the docs ================= Check out the `gh-pages `_ branch and follow the ``README.rst`` there. Developers ========== Testing ------- First install the development requirements:: $> pip install -r requirements-dev.txt The run the tests for all Python versions on your system:: $> python sh.py test To run a single test for all environments:: $> python sh.py test FunctionalTests.test_unicode_arg To run a single test for a single environment:: $> python sh.py test -e 3.4 FunctionalTests.test_unicode_arg Coverage -------- First run all of the tests:: $> python sh.py test This will aggregate a ``.coverage``. You may then visualize the report with:: $> coverage report Or generate visual html files with:: $> coverage html Which will create ``./htmlcov/index.html`` that you may open in a web browser. Keywords: subprocess,process,shell,launch,program Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.1 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Software Development :: Build Tools Classifier: Topic :: Software Development :: Libraries :: Python Modules python-sh-1.12.14/README.rst000066400000000000000000000037711334350127300153110ustar00rootroot00000000000000.. image:: https://raw.githubusercontent.com/amoffat/sh/master/logo-230.png :target: https://amoffat.github.com/sh :alt: Logo | .. image:: https://img.shields.io/pypi/v/sh.svg?style=flat-square :target: https://pypi.python.org/pypi/sh :alt: Version .. image:: https://img.shields.io/pypi/pyversions/sh.svg?style=flat-square :target: https://pypi.python.org/pypi/sh :alt: Python Versions .. image:: https://img.shields.io/travis/amoffat/sh/master.svg?style=flat-square :target: https://travis-ci.org/amoffat/sh :alt: Build Status .. image:: https://img.shields.io/coveralls/amoffat/sh.svg?style=flat-square :target: https://coveralls.io/r/amoffat/sh?branch=master :alt: Coverage Status | sh is a full-fledged subprocess replacement for Python 2.6 - 3.6, PyPy and PyPy3 that allows you to call any program as if it were a function: .. code:: python from sh import ifconfig print ifconfig("eth0") sh is *not* a collection of system commands implemented in Python. `Complete documentation here`_ Installation ============ :: $> pip install sh Updating the docs ================= Check out the `gh-pages `_ branch and follow the ``README.rst`` there. Developers ========== Testing ------- First install the development requirements:: $> pip install -r requirements-dev.txt The run the tests for all Python versions on your system:: $> python sh.py test To run a single test for all environments:: $> python sh.py test FunctionalTests.test_unicode_arg To run a single test for a single environment:: $> python sh.py test -e 3.4 FunctionalTests.test_unicode_arg Coverage -------- First run all of the tests:: $> python sh.py test This will aggregate a ``.coverage``. You may then visualize the report with:: $> coverage report Or generate visual html files with:: $> coverage html Which will create ``./htmlcov/index.html`` that you may open in a web browser. python-sh-1.12.14/setup.cfg000066400000000000000000000001771334350127300154400ustar00rootroot00000000000000[bdist_wheel] universal = 1 [metadata] license_file = LICENSE.txt [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 python-sh-1.12.14/setup.py000066400000000000000000000034731334350127300153330ustar00rootroot00000000000000from __future__ import print_function import os from os.path import dirname, abspath, join import sys import sh import codecs from setuptools import setup HERE = dirname(abspath(__file__)) author = "Andrew Moffat" author_email = "andrew.robert.moffat@gmail.com" keywords = ["subprocess", "process", "shell", "launch", "program"] def read(*parts): with codecs.open(join(HERE, *parts), "rb", "utf-8") as f: return f.read() setup( name="sh", version=sh.__version__, description="Python subprocess replacement", long_description=read("README.rst"), author=author, author_email=author_email, maintainer=author, maintainer_email=author_email, keywords=keywords, url="https://github.com/amoffat/sh", license="MIT", py_modules=["sh"], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: System Administrators", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.1", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: Implementation :: CPython", "Programming Language :: Python :: Implementation :: PyPy", "Topic :: Software Development :: Build Tools", "Topic :: Software Development :: Libraries :: Python Modules", ], ) python-sh-1.12.14/sh.egg-info/000077500000000000000000000000001334350127300157165ustar00rootroot00000000000000python-sh-1.12.14/sh.egg-info/PKG-INFO000066400000000000000000000077161334350127300170260ustar00rootroot00000000000000Metadata-Version: 1.1 Name: sh Version: 1.12.14 Summary: Python subprocess replacement Home-page: https://github.com/amoffat/sh Author: Andrew Moffat Author-email: andrew.robert.moffat@gmail.com License: MIT Description: .. image:: https://raw.githubusercontent.com/amoffat/sh/master/logo-230.png :target: https://amoffat.github.com/sh :alt: Logo | .. image:: https://img.shields.io/pypi/v/sh.svg?style=flat-square :target: https://pypi.python.org/pypi/sh :alt: Version .. image:: https://img.shields.io/pypi/pyversions/sh.svg?style=flat-square :target: https://pypi.python.org/pypi/sh :alt: Python Versions .. image:: https://img.shields.io/travis/amoffat/sh/master.svg?style=flat-square :target: https://travis-ci.org/amoffat/sh :alt: Build Status .. image:: https://img.shields.io/coveralls/amoffat/sh.svg?style=flat-square :target: https://coveralls.io/r/amoffat/sh?branch=master :alt: Coverage Status | sh is a full-fledged subprocess replacement for Python 2.6 - 3.6, PyPy and PyPy3 that allows you to call any program as if it were a function: .. code:: python from sh import ifconfig print ifconfig("eth0") sh is *not* a collection of system commands implemented in Python. `Complete documentation here`_ Installation ============ :: $> pip install sh Updating the docs ================= Check out the `gh-pages `_ branch and follow the ``README.rst`` there. Developers ========== Testing ------- First install the development requirements:: $> pip install -r requirements-dev.txt The run the tests for all Python versions on your system:: $> python sh.py test To run a single test for all environments:: $> python sh.py test FunctionalTests.test_unicode_arg To run a single test for a single environment:: $> python sh.py test -e 3.4 FunctionalTests.test_unicode_arg Coverage -------- First run all of the tests:: $> python sh.py test This will aggregate a ``.coverage``. You may then visualize the report with:: $> coverage report Or generate visual html files with:: $> coverage html Which will create ``./htmlcov/index.html`` that you may open in a web browser. Keywords: subprocess,process,shell,launch,program Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Console Classifier: Intended Audience :: Developers Classifier: Intended Audience :: System Administrators Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.6 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.1 Classifier: Programming Language :: Python :: 3.2 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Programming Language :: Python :: 3.6 Classifier: Programming Language :: Python :: Implementation :: CPython Classifier: Programming Language :: Python :: Implementation :: PyPy Classifier: Topic :: Software Development :: Build Tools Classifier: Topic :: Software Development :: Libraries :: Python Modules python-sh-1.12.14/sh.egg-info/SOURCES.txt000066400000000000000000000003151334350127300176010ustar00rootroot00000000000000CHANGELOG.md LICENSE.txt MANIFEST.in README.rst setup.cfg setup.py sh.py test.py sh.egg-info/PKG-INFO sh.egg-info/SOURCES.txt sh.egg-info/dependency_links.txt sh.egg-info/pbr.json sh.egg-info/top_level.txtpython-sh-1.12.14/sh.egg-info/dependency_links.txt000066400000000000000000000000011334350127300217640ustar00rootroot00000000000000 python-sh-1.12.14/sh.egg-info/pbr.json000066400000000000000000000000571334350127300173760ustar00rootroot00000000000000{"is_release": false, "git_version": "93eca5d"}python-sh-1.12.14/sh.egg-info/top_level.txt000066400000000000000000000000031334350127300204410ustar00rootroot00000000000000sh python-sh-1.12.14/sh.py000066400000000000000000003540571334350127300146140ustar00rootroot00000000000000""" http://amoffat.github.io/sh/ """ #=============================================================================== # Copyright (C) 2011-2017 by Andrew Moffat # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. #=============================================================================== __version__ = "1.12.14" __project_url__ = "https://github.com/amoffat/sh" import platform if "windows" in platform.system().lower(): # pragma: no cover raise ImportError("sh %s is currently only supported on linux and osx. \ please install pbs 0.110 (http://pypi.python.org/pypi/pbs) for windows \ support." % __version__) import sys IS_PY3 = sys.version_info[0] == 3 MINOR_VER = sys.version_info[1] IS_PY26 = sys.version_info[0] == 2 and MINOR_VER == 6 import traceback import os import re import time import getpass from types import ModuleType, GeneratorType from functools import partial import inspect import tempfile import stat import glob as glob_module import ast from contextlib import contextmanager import pwd import errno from io import UnsupportedOperation, open as fdopen from locale import getpreferredencoding DEFAULT_ENCODING = getpreferredencoding() or "UTF-8" # normally i would hate this idea of using a global to signify whether we are # running tests, because it breaks the assumption that what is running in the # tests is what will run live, but we ONLY use this in a place that has no # serious side-effects that could change anything. as long as we do that, it # should be ok RUNNING_TESTS = bool(int(os.environ.get("SH_TESTS_RUNNING", "0"))) FORCE_USE_SELECT = bool(int(os.environ.get("SH_TESTS_USE_SELECT", "0"))) if IS_PY3: from io import StringIO ioStringIO = StringIO from io import BytesIO as cStringIO iocStringIO = cStringIO from queue import Queue, Empty # for some reason, python 3.1 removed the builtin "callable", wtf if not hasattr(__builtins__, "callable"): def callable(ob): return hasattr(ob, "__call__") else: from StringIO import StringIO from cStringIO import OutputType as cStringIO from io import StringIO as ioStringIO from io import BytesIO as iocStringIO from Queue import Queue, Empty IS_OSX = platform.system() == "Darwin" THIS_DIR = os.path.dirname(os.path.realpath(__file__)) SH_LOGGER_NAME = __name__ import errno import pty import termios import signal import gc import select import threading import tty import fcntl import struct import resource from collections import deque import logging import weakref # a re-entrant lock for pushd. this way, multiple threads that happen to use # pushd will all see the current working directory for the duration of the # with-context PUSHD_LOCK = threading.RLock() if hasattr(inspect, "getfullargspec"): def get_num_args(fn): return len(inspect.getfullargspec(fn).args) else: def get_num_args(fn): return len(inspect.getargspec(fn).args) if IS_PY3: raw_input = input unicode = str basestring = str long = int _unicode_methods = set(dir(unicode())) HAS_POLL = hasattr(select, "poll") POLLER_EVENT_READ = 1 POLLER_EVENT_WRITE = 2 POLLER_EVENT_HUP = 4 POLLER_EVENT_ERROR = 8 # here we use an use a poller interface that transparently selects the most # capable poller (out of either select.select or select.poll). this was added # by zhangyafeikimi when he discovered that if the fds created internally by sh # numbered > 1024, select.select failed (a limitation of select.select). this # can happen if your script opens a lot of files if HAS_POLL and not FORCE_USE_SELECT: class Poller(object): def __init__(self): self._poll = select.poll() # file descriptor <-> file object bidirectional maps self.fd_lookup = {} self.fo_lookup = {} def __nonzero__(self): return len(self.fd_lookup) != 0 def __len__(self): return len(self.fd_lookup) def _set_fileobject(self, f): if hasattr(f, "fileno"): fd = f.fileno() self.fd_lookup[fd] = f self.fo_lookup[f] = fd else: self.fd_lookup[f] = f self.fo_lookup[f] = f def _remove_fileobject(self, f): if hasattr(f, "fileno"): fd = f.fileno() del self.fd_lookup[fd] del self.fo_lookup[f] else: del self.fd_lookup[f] del self.fo_lookup[f] def _get_file_descriptor(self, f): return self.fo_lookup.get(f) def _get_file_object(self, fd): return self.fd_lookup.get(fd) def _register(self, f, events): # f can be a file descriptor or file object self._set_fileobject(f) fd = self._get_file_descriptor(f) self._poll.register(fd, events) def register_read(self, f): self._register(f, select.POLLIN | select.POLLPRI) def register_write(self, f): self._register(f, select.POLLOUT) def register_error(self, f): self._register(f, select.POLLERR | select.POLLHUP | select.POLLNVAL) def unregister(self, f): fd = self._get_file_descriptor(f) self._poll.unregister(fd) self._remove_fileobject(f) def poll(self, timeout): if timeout is not None: # convert from seconds to milliseconds timeout *= 1000 changes = self._poll.poll(timeout) results = [] for fd, events in changes: f = self._get_file_object(fd) if events & (select.POLLIN | select.POLLPRI): results.append((f, POLLER_EVENT_READ)) elif events & (select.POLLOUT): results.append((f, POLLER_EVENT_WRITE)) elif events & (select.POLLHUP): results.append((f, POLLER_EVENT_HUP)) elif events & (select.POLLERR | select.POLLNVAL): results.append((f, POLLER_EVENT_ERROR)) return results else: class Poller(object): def __init__(self): self.rlist = [] self.wlist = [] self.xlist = [] def __nonzero__(self): return len(self.rlist) + len(self.wlist) + len(self.xlist) != 0 def __len__(self): return len(self.rlist) + len(self.wlist) + len(self.xlist) def _register(self, f, l): if f not in l: l.append(f) def _unregister(self, f, l): if f in l: l.remove(f) def register_read(self, f): self._register(f, self.rlist) def register_write(self, f): self._register(f, self.wlist) def register_error(self, f): self._register(f, self.xlist) def unregister(self, f): self._unregister(f, self.rlist) self._unregister(f, self.wlist) self._unregister(f, self.xlist) def poll(self, timeout): _in, _out, _err = select.select(self.rlist, self.wlist, self.xlist, timeout) results = [] for f in _in: results.append((f, POLLER_EVENT_READ)) for f in _out: results.append((f, POLLER_EVENT_WRITE)) for f in _err: results.append((f, POLLER_EVENT_ERROR)) return results def encode_to_py3bytes_or_py2str(s): """ takes anything and attempts to return a py2 string or py3 bytes. this is typically used when creating command + arguments to be executed via os.exec* """ fallback_encoding = "utf8" if IS_PY3: # if we're already bytes, do nothing if isinstance(s, bytes): pass else: s = str(s) try: s = bytes(s, DEFAULT_ENCODING) except UnicodeEncodeError: s = bytes(s, fallback_encoding) else: # attempt to convert the thing to unicode from the system's encoding try: s = unicode(s, DEFAULT_ENCODING) # if the thing is already unicode, or it's a number, it can't be # coerced to unicode with an encoding argument, but if we leave out # the encoding argument, it will convert it to a string, then to unicode except TypeError: s = unicode(s) # now that we have guaranteed unicode, encode to our system encoding, # but attempt to fall back to something try: s = s.encode(DEFAULT_ENCODING) except: s = s.encode(fallback_encoding, "replace") return s def _indent_text(text, num=4): lines = [] for line in text.split("\n"): line = (" " * num) + line lines.append(line) return "\n".join(lines) class ForkException(Exception): def __init__(self, orig_exc): tmpl = """ Original exception: =================== %s """ msg = tmpl % _indent_text(orig_exc) Exception.__init__(self, msg) class ErrorReturnCodeMeta(type): """ a metaclass which provides the ability for an ErrorReturnCode (or derived) instance, imported from one sh module, to be considered the subclass of ErrorReturnCode from another module. this is mostly necessary in the tests, where we do assertRaises, but the ErrorReturnCode that the program we're testing throws may not be the same class that we pass to assertRaises """ def __subclasscheck__(self, o): other_bases = set([b.__name__ for b in o.__bases__]) return self.__name__ in other_bases or o.__name__ == self.__name__ class ErrorReturnCode(Exception): __metaclass__ = ErrorReturnCodeMeta """ base class for all exceptions as a result of a command's exit status being deemed an error. this base class is dynamically subclassed into derived classes with the format: ErrorReturnCode_NNN where NNN is the exit code number. the reason for this is it reduces boiler plate code when testing error return codes: try: some_cmd() except ErrorReturnCode_12: print("couldn't do X") vs: try: some_cmd() except ErrorReturnCode as e: if e.exit_code == 12: print("couldn't do X") it's not much of a savings, but i believe it makes the code easier to read """ truncate_cap = 750 def __init__(self, full_cmd, stdout, stderr, truncate=True): self.full_cmd = full_cmd self.stdout = stdout self.stderr = stderr exc_stdout = self.stdout if truncate: exc_stdout = exc_stdout[:self.truncate_cap] out_delta = len(self.stdout) - len(exc_stdout) if out_delta: exc_stdout += ("... (%d more, please see e.stdout)" % out_delta).encode() exc_stderr = self.stderr if truncate: exc_stderr = exc_stderr[:self.truncate_cap] err_delta = len(self.stderr) - len(exc_stderr) if err_delta: exc_stderr += ("... (%d more, please see e.stderr)" % err_delta).encode() msg_tmpl = unicode("\n\n RAN: {cmd}\n\n STDOUT:\n{stdout}\n\n STDERR:\n{stderr}") msg = msg_tmpl.format( cmd=self.full_cmd, stdout=exc_stdout.decode(DEFAULT_ENCODING, "replace"), stderr=exc_stderr.decode(DEFAULT_ENCODING, "replace") ) super(ErrorReturnCode, self).__init__(msg) class SignalException(ErrorReturnCode): pass class TimeoutException(Exception): """ the exception thrown when a command is killed because a specified timeout (via _timeout) was hit """ def __init__(self, exit_code): self.exit_code = exit_code super(Exception, self).__init__() SIGNALS_THAT_SHOULD_THROW_EXCEPTION = set(( signal.SIGABRT, signal.SIGBUS, signal.SIGFPE, signal.SIGILL, signal.SIGINT, signal.SIGKILL, signal.SIGPIPE, signal.SIGQUIT, signal.SIGSEGV, signal.SIGTERM, signal.SIGSYS, )) # we subclass AttributeError because: # https://github.com/ipython/ipython/issues/2577 # https://github.com/amoffat/sh/issues/97#issuecomment-10610629 class CommandNotFound(AttributeError): pass rc_exc_regex = re.compile("(ErrorReturnCode|SignalException)_((\d+)|SIG[a-zA-Z]+)") rc_exc_cache = {} SIGNAL_MAPPING = {} for k,v in signal.__dict__.items(): if re.match(r"SIG[a-zA-Z]+", k): SIGNAL_MAPPING[v] = k def get_exc_from_name(name): """ takes an exception name, like: ErrorReturnCode_1 SignalException_9 SignalException_SIGHUP and returns the corresponding exception. this is primarily used for importing exceptions from sh into user code, for instance, to capture those exceptions """ exc = None try: return rc_exc_cache[name] except KeyError: m = rc_exc_regex.match(name) if m: base = m.group(1) rc_or_sig_name = m.group(2) if base == "SignalException": try: rc = -int(rc_or_sig_name) except ValueError: rc = -getattr(signal, rc_or_sig_name) else: rc = int(rc_or_sig_name) exc = get_rc_exc(rc) return exc def get_rc_exc(rc): """ takes a exit code or negative signal number and produces an exception that corresponds to that return code. positive return codes yield ErrorReturnCode exception, negative return codes yield SignalException we also cache the generated exception so that only one signal of that type exists, preserving identity """ try: return rc_exc_cache[rc] except KeyError: pass if rc > 0: name = "ErrorReturnCode_%d" % rc base = ErrorReturnCode else: signame = SIGNAL_MAPPING[abs(rc)] name = "SignalException_" + signame base = SignalException exc = ErrorReturnCodeMeta(name, (base,), {"exit_code": rc}) rc_exc_cache[rc] = exc return exc # we monkey patch glob. i'm normally generally against monkey patching, but i # decided to do this really un-intrusive patch because we need a way to detect # if a list that we pass into an sh command was generated from glob. the reason # being that glob returns an empty list if a pattern is not found, and so # commands will treat the empty list as no arguments, which can be a problem, # ie: # # ls(glob("*.ojfawe")) # # ^ will show the contents of your home directory, because it's essentially # running ls([]) which, as a process, is just "ls". # # so we subclass list and monkey patch the glob function. nobody should be the # wiser, but we'll have results that we can make some determinations on _old_glob = glob_module.glob class GlobResults(list): def __init__(self, path, results): self.path = path list.__init__(self, results) def glob(path, *args, **kwargs): expanded = GlobResults(path, _old_glob(path, *args, **kwargs)) return expanded glob_module.glob = glob def which(program, paths=None): """ takes a program name or full path, plus an optional collection of search paths, and returns the full path of the requested executable. if paths is specified, it is the entire list of search paths, and the PATH env is not used at all. otherwise, PATH env is used to look for the program """ def is_exe(fpath): return (os.path.exists(fpath) and os.access(fpath, os.X_OK) and os.path.isfile(os.path.realpath(fpath))) found_path = None fpath, fname = os.path.split(program) # if there's a path component, then we've specified a path to the program, # and we should just test if that program is executable. if it is, return if fpath: program = os.path.abspath(os.path.expanduser(program)) if is_exe(program): found_path = program # otherwise, we've just passed in the program name, and we need to search # the paths to find where it actually lives else: paths_to_search = [] if isinstance(paths, (tuple, list)): paths_to_search.extend(paths) else: env_paths = os.environ.get("PATH", "").split(os.pathsep) paths_to_search.extend(env_paths) for path in paths_to_search: exe_file = os.path.join(path, program) if is_exe(exe_file): found_path = exe_file break return found_path def resolve_command_path(program): path = which(program) if not path: # our actual command might have a dash in it, but we can't call # that from python (we have to use underscores), so we'll check # if a dash version of our underscore command exists and use that # if it does if "_" in program: path = which(program.replace("_", "-")) if not path: return None return path def resolve_command(name, baked_args=None): path = resolve_command_path(name) cmd = None if path: cmd = Command(path) if baked_args: cmd = cmd.bake(**baked_args) return cmd class Logger(object): """ provides a memory-inexpensive logger. a gotcha about python's builtin logger is that logger objects are never garbage collected. if you create a thousand loggers with unique names, they'll sit there in memory until your script is done. with sh, it's easy to create loggers with unique names if we want our loggers to include our command arguments. for example, these are all unique loggers: ls -l ls -l /tmp ls /tmp so instead of creating unique loggers, and without sacrificing logging output, we use this class, which maintains as part of its state, the logging "context", which will be the very unique name. this allows us to get a logger with a very general name, eg: "command", and have a unique name appended to it via the context, eg: "ls -l /tmp" """ def __init__(self, name, context=None): self.name = name self.log = logging.getLogger("%s.%s" % (SH_LOGGER_NAME, name)) self.set_context(context) def _format_msg(self, msg, *args): if self.context: msg = "%s: %s" % (self.context, msg) return msg % args def set_context(self, context): if context: context = context.replace("%", "%%") self.context = context or "" def get_child(self, name, context): new_name = self.name + "." + name new_context = self.context + "." + context l = Logger(new_name, new_context) return l def info(self, msg, *args): self.log.info(self._format_msg(msg, *args)) def debug(self, msg, *args): self.log.debug(self._format_msg(msg, *args)) def error(self, msg, *args): self.log.error(self._format_msg(msg, *args)) def exception(self, msg, *args): self.log.exception(self._format_msg(msg, *args)) def default_logger_str(cmd, call_args, pid=None): if pid: s = "" % (cmd, pid) else: s = "" % cmd return s class RunningCommand(object): """ this represents an executing Command object. it is returned as the result of __call__() being executed on a Command instance. this creates a reference to a OProc instance, which is a low-level wrapper around the process that was exec'd this is the class that gets manipulated the most by user code, and so it implements various convenience methods and logical mechanisms for the underlying process. for example, if a user tries to access a backgrounded-process's stdout/err, the RunningCommand object is smart enough to know to wait() on the process to finish first. and when the process finishes, RunningCommand is smart enough to translate exit codes to exceptions. """ # these are attributes that we allow to passthrough to OProc for _OProc_attr_whitelist = set(( "signal", "terminate", "kill", "kill_group", "signal_group", "pid", "sid", "pgid", "ctty", "input_thread_exc", "output_thread_exc", "bg_thread_exc", )) def __init__(self, cmd, call_args, stdin, stdout, stderr): """ cmd is an array, where each element is encoded as bytes (PY3) or str (PY2) """ # self.ran is used for auditing what actually ran. for example, in # exceptions, or if you just want to know what was ran after the # command ran # # here we're making a consistent unicode string out if our cmd. # we're also assuming (correctly, i think) that the command and its # arguments are the encoding we pass into _encoding, which falls back to # the system's encoding enc = call_args["encoding"] self.ran = " ".join([arg.decode(enc, "ignore") for arg in cmd]) self.call_args = call_args self.cmd = cmd self.process = None self._process_completed = False should_wait = True spawn_process = True # this is used to track if we've already raised StopIteration, and if we # have, raise it immediately again if the user tries to call next() on # us. https://github.com/amoffat/sh/issues/273 self._stopped_iteration = False # with contexts shouldn't run at all yet, they prepend # to every command in the context if call_args["with"]: spawn_process = False get_prepend_stack().append(self) if call_args["piped"] or call_args["iter"] or call_args["iter_noblock"]: should_wait = False # we're running in the background, return self and let us lazily # evaluate if call_args["bg"]: should_wait = False # redirection if call_args["err_to_out"]: stderr = OProc.STDOUT done_callback = call_args["done"] if done_callback: call_args["done"] = partial(done_callback, self) # set up which stream should write to the pipe # TODO, make pipe None by default and limit the size of the Queue # in oproc.OProc pipe = OProc.STDOUT if call_args["iter"] == "out" or call_args["iter"] is True: pipe = OProc.STDOUT elif call_args["iter"] == "err": pipe = OProc.STDERR if call_args["iter_noblock"] == "out" or call_args["iter_noblock"] is True: pipe = OProc.STDOUT elif call_args["iter_noblock"] == "err": pipe = OProc.STDERR # there's currently only one case where we wouldn't spawn a child # process, and that's if we're using a with-context with our command self._spawned_and_waited = False if spawn_process: log_str_factory = call_args["log_msg"] or default_logger_str logger_str = log_str_factory(self.ran, call_args) self.log = Logger("command", logger_str) self.log.info("starting process") if should_wait: self._spawned_and_waited = True # this lock is needed because of a race condition where a background # thread, created in the OProc constructor, may try to access # self.process, but it has not been assigned yet process_assign_lock = threading.Lock() with process_assign_lock: self.process = OProc(self, self.log, cmd, stdin, stdout, stderr, self.call_args, pipe, process_assign_lock) logger_str = log_str_factory(self.ran, call_args, self.process.pid) self.log.set_context(logger_str) self.log.info("process started") if should_wait: self.wait() def wait(self): """ waits for the running command to finish. this is called on all running commands, eventually, except for ones that run in the background """ if not self._process_completed: self._process_completed = True exit_code = self.process.wait() if self.process.timed_out: # if we timed out, our exit code represents a signal, which is # negative, so let's make it positive to store in our # TimeoutException raise TimeoutException(-exit_code) else: self.handle_command_exit_code(exit_code) # if an iterable command is using an instance of OProc for its stdin, # wait on it. the process is probably set to "piped", which means it # won't be waited on, which means exceptions won't propagate up to the # main thread. this allows them to bubble up if self.process._stdin_process: self.process._stdin_process.command.wait() self.log.info("process completed") return self def handle_command_exit_code(self, code): """ here we determine if we had an exception, or an error code that we weren't expecting to see. if we did, we create and raise an exception """ ca = self.call_args exc_class = get_exc_exit_code_would_raise(code, ca["ok_code"], ca["piped"]) if exc_class: exc = exc_class(self.ran, self.process.stdout, self.process.stderr, ca["truncate_exc"]) raise exc @property def stdout(self): self.wait() return self.process.stdout @property def stderr(self): self.wait() return self.process.stderr @property def exit_code(self): self.wait() return self.process.exit_code def __len__(self): return len(str(self)) def __enter__(self): """ we don't actually do anything here because anything that should have been done would have been done in the Command.__call__ call. essentially all that has to happen is the comand be pushed on the prepend stack. """ pass def __iter__(self): return self def next(self): """ allow us to iterate over the output of our command """ if self._stopped_iteration: raise StopIteration() # we do this because if get blocks, we can't catch a KeyboardInterrupt # so the slight timeout allows for that. while True: try: chunk = self.process._pipe_queue.get(True, 0.001) except Empty: if self.call_args["iter_noblock"]: return errno.EWOULDBLOCK else: if chunk is None: self.wait() self._stopped_iteration = True raise StopIteration() try: return chunk.decode(self.call_args["encoding"], self.call_args["decode_errors"]) except UnicodeDecodeError: return chunk # python 3 __next__ = next def __exit__(self, typ, value, traceback): if self.call_args["with"] and get_prepend_stack(): get_prepend_stack().pop() def __str__(self): """ in python3, should return unicode. in python2, should return a string of bytes """ if IS_PY3: return self.__unicode__() else: return unicode(self).encode(self.call_args["encoding"]) def __unicode__(self): """ a magic method defined for python2. calling unicode() on a RunningCommand object will call this """ if self.process and self.stdout: return self.stdout.decode(self.call_args["encoding"], self.call_args["decode_errors"]) elif IS_PY3: return "" else: return unicode("") def __eq__(self, other): return unicode(self) == unicode(other) __hash__ = None # Avoid DeprecationWarning in Python < 3 def __contains__(self, item): return item in str(self) def __getattr__(self, p): # let these three attributes pass through to the OProc object if p in self._OProc_attr_whitelist: if self.process: return getattr(self.process, p) else: raise AttributeError # see if strings have what we're looking for. we're looking at the # method names explicitly because we don't want to evaluate self unless # we absolutely have to, the reason being, in python2, hasattr swallows # exceptions, and if we try to run hasattr on a command that failed and # is being run with _iter=True, the command will be evaluated, throw an # exception, but hasattr will discard it if p in _unicode_methods: return getattr(unicode(self), p) raise AttributeError def __repr__(self): """ in python3, should return unicode. in python2, should return a string of bytes """ try: return str(self) except UnicodeDecodeError: if self.process: if self.stdout: return repr(self.stdout) return repr("") def __long__(self): return long(str(self).strip()) def __float__(self): return float(str(self).strip()) def __int__(self): return int(str(self).strip()) def output_redirect_is_filename(out): return isinstance(out, basestring) def get_prepend_stack(): tl = Command.thread_local if not hasattr(tl, "_prepend_stack"): tl._prepend_stack = [] return tl._prepend_stack def special_kwarg_validator(kwargs, invalid_list): s1 = set(kwargs.keys()) invalid_args = [] for args in invalid_list: if callable(args): fn = args ret = fn(kwargs) invalid_args.extend(ret) else: args, error_msg = args if s1.issuperset(args): invalid_args.append((args, error_msg)) return invalid_args def get_fileno(ob): # in py2, this will return None. in py3, it will return an method that # raises when called fileno_meth = getattr(ob, "fileno", None) fileno = None if fileno_meth: # py3 StringIO objects will report a fileno, but calling it will raise # an exception try: fileno = fileno_meth() except UnsupportedOperation: pass elif isinstance(ob, (int,long)) and ob >= 0: fileno = ob return fileno def ob_is_tty(ob): """ checks if an object (like a file-like object) is a tty. """ fileno = get_fileno(ob) is_tty = False if fileno: is_tty = os.isatty(fileno) return is_tty def ob_is_pipe(ob): fileno = get_fileno(ob) is_pipe = False if fileno: fd_stat = os.fstat(fileno) is_pipe = stat.S_ISFIFO(fd_stat.st_mode) return is_pipe def tty_in_validator(kwargs): pairs = (("tty_in", "in"), ("tty_out", "out")) invalid = [] for tty, std in pairs: if tty in kwargs and ob_is_tty(kwargs.get(std, None)): args = (tty, std) error = "`_%s` is a TTY already, so so it doesn't make sense \ to set up a TTY with `_%s`" % (std, tty) invalid.append((args, error)) return invalid def bufsize_validator(kwargs): """ a validator to prevent a user from saying that they want custom buffering when they're using an in/out object that will be os.dup'd to the process, and has its own buffering. an example is a pipe or a tty. it doesn't make sense to tell them to have a custom buffering, since the os controls this. """ invalid = [] in_ob = kwargs.get("in", None) out_ob = kwargs.get("out", None) in_buf = kwargs.get("in_bufsize", None) out_buf = kwargs.get("out_bufsize", None) in_no_buf = ob_is_tty(in_ob) or ob_is_pipe(in_ob) out_no_buf = ob_is_tty(out_ob) or ob_is_pipe(out_ob) err = "Can't specify an {target} bufsize if the {target} target is a pipe or TTY" if in_no_buf and in_buf is not None: invalid.append((("in", "in_bufsize"), err.format(target="in"))) if out_no_buf and out_buf is not None: invalid.append((("out", "out_bufsize"), err.format(target="out"))) return invalid class Command(object): """ represents an un-run system program, like "ls" or "cd". because it represents the program itself (and not a running instance of it), it should hold very little state. in fact, the only state it does hold is baked arguments. when a Command object is called, the result that is returned is a RunningCommand object, which represents the Command put into an execution state. """ thread_local = threading.local() _call_args = { "fg": False, # run command in foreground # run a command in the background. commands run in the background # ignore SIGHUP and do not automatically exit when the parent process # ends "bg": False, # automatically report exceptions for background commands "bg_exc": True, "with": False, # prepend the command to every command after it "in": None, "out": None, # redirect STDOUT "err": None, # redirect STDERR "err_to_out": None, # redirect STDERR to STDOUT # stdin buffer size # 1 for line, 0 for unbuffered, any other number for that amount "in_bufsize": 0, # stdout buffer size, same values as above "out_bufsize": 1, "err_bufsize": 1, # this is how big the output buffers will be for stdout and stderr. # this is essentially how much output they will store from the process. # we use a deque, so if it overflows past this amount, the first items # get pushed off as each new item gets added. # # NOTICE # this is not a *BYTE* size, this is a *CHUNK* size...meaning, that if # you're buffering out/err at 1024 bytes, the internal buffer size will # be "internal_bufsize" CHUNKS of 1024 bytes "internal_bufsize": 3 * 1024 ** 2, "env": None, "piped": None, "iter": None, "iter_noblock": None, "ok_code": 0, "cwd": None, # the separator delimiting between a long-argument's name and its value # setting this to None will cause name and value to be two separate # arguments, like for short options # for example, --arg=derp, '=' is the long_sep "long_sep": "=", # the prefix used for long arguments "long_prefix": "--", # this is for programs that expect their input to be from a terminal. # ssh is one of those programs "tty_in": False, "tty_out": True, "encoding": DEFAULT_ENCODING, "decode_errors": "strict", # how long the process should run before it is auto-killed "timeout": None, "timeout_signal": signal.SIGKILL, # TODO write some docs on "long-running processes" # these control whether or not stdout/err will get aggregated together # as the process runs. this has memory usage implications, so sometimes # with long-running processes with a lot of data, it makes sense to # set these to true "no_out": False, "no_err": False, "no_pipe": False, # if any redirection is used for stdout or stderr, internal buffering # of that data is not stored. this forces it to be stored, as if # the output is being T'd to both the redirected destination and our # internal buffers "tee": None, # will be called when a process terminates regardless of exception "done": None, # a tuple (rows, columns) of the desired size of both the stdout and # stdin ttys, if ttys are being used "tty_size": (20, 80), # whether or not our exceptions should be truncated "truncate_exc": True, # a function to call after the child forks but before the process execs "preexec_fn": None, # UID to set after forking. Requires root privileges. Not supported on # Windows. "uid": None, # put the forked process in its own process session? "new_session": True, # pre-process args passed into __call__. only really useful when used # in .bake() "arg_preprocess": None, # a callable that produces a log message from an argument tuple of the # command and the args "log_msg": None, } # this is a collection of validators to make sure the special kwargs make # sense _kwarg_validators = ( (("fg", "bg"), "Command can't be run in the foreground and background"), (("fg", "err_to_out"), "Can't redirect STDERR in foreground mode"), (("err", "err_to_out"), "Stderr is already being redirected"), (("piped", "iter"), "You cannot iterate when this command is being piped"), (("piped", "no_pipe"), "Using a pipe doesn't make sense if you've \ disabled the pipe"), (("no_out", "iter"), "You cannot iterate over output if there is no \ output"), tty_in_validator, bufsize_validator, ) def __init__(self, path, search_paths=None): found = which(path, search_paths) self._path = encode_to_py3bytes_or_py2str("") # is the command baked (aka, partially applied)? self._partial = False self._partial_baked_args = [] self._partial_call_args = {} # bugfix for functools.wraps. issue #121 self.__name__ = str(self) if not found: raise CommandNotFound(path) # the reason why we set the values early in the constructor, and again # here, is for people who have tools that inspect the stack on # exception. if CommandNotFound is raised, we need self._path and the # other attributes to be set correctly, so repr() works when they're # inspecting the stack. issue #304 self._path = encode_to_py3bytes_or_py2str(found) self.__name__ = str(self) def __getattribute__(self, name): # convenience getattr = partial(object.__getattribute__, self) val = None if name.startswith("_"): val = getattr(name) elif name == "bake": val = getattr("bake") # here we have a way of getting past shadowed subcommands. for example, # if "git bake" was a thing, we wouldn't be able to do `git.bake()` # because `.bake()` is already a method. so we allow `git.bake_()` elif name.endswith("_"): name = name[:-1] if val is None: val = getattr("bake")(name) return val @staticmethod def _extract_call_args(kwargs): """ takes kwargs that were passed to a command's __call__ and extracts out the special keyword arguments, we return a tuple of special keyword args, and kwargs that will go to the execd command """ kwargs = kwargs.copy() call_args = {} for parg, default in Command._call_args.items(): key = "_" + parg if key in kwargs: call_args[parg] = kwargs[key] del kwargs[key] invalid_kwargs = special_kwarg_validator(call_args, Command._kwarg_validators) if invalid_kwargs: exc_msg = [] for args, error_msg in invalid_kwargs: exc_msg.append(" %r: %s" % (args, error_msg)) exc_msg = "\n".join(exc_msg) raise TypeError("Invalid special arguments:\n\n%s\n" % exc_msg) return call_args, kwargs # TODO needs documentation def bake(self, *args, **kwargs): fn = type(self)(self._path) fn._partial = True call_args, kwargs = self._extract_call_args(kwargs) pruned_call_args = call_args for k, v in Command._call_args.items(): try: if pruned_call_args[k] == v: del pruned_call_args[k] except KeyError: continue fn._partial_call_args.update(self._partial_call_args) fn._partial_call_args.update(pruned_call_args) fn._partial_baked_args.extend(self._partial_baked_args) sep = pruned_call_args.get("long_sep", self._call_args["long_sep"]) prefix = pruned_call_args.get("long_prefix", self._call_args["long_prefix"]) fn._partial_baked_args.extend(compile_args(args, kwargs, sep, prefix)) return fn def __str__(self): """ in python3, should return unicode. in python2, should return a string of bytes """ if IS_PY3: return self.__unicode__() else: return self.__unicode__().encode(DEFAULT_ENCODING) def __eq__(self, other): return str(self) == str(other) __hash__ = None # Avoid DeprecationWarning in Python < 3 def __repr__(self): """ in python3, should return unicode. in python2, should return a string of bytes """ return "" % str(self) def __unicode__(self): """ a magic method defined for python2. calling unicode() on a self will call this """ baked_args = " ".join(item.decode(DEFAULT_ENCODING) for item in self._partial_baked_args) if baked_args: baked_args = " " + baked_args return self._path.decode(DEFAULT_ENCODING) + baked_args def __enter__(self): self(_with=True) def __exit__(self, typ, value, traceback): get_prepend_stack().pop() def __call__(self, *args, **kwargs): kwargs = kwargs.copy() args = list(args) # this will hold our final command, including arguments, that will be # execd cmd = [] # this will hold a complete mapping of all our special keyword arguments # and their values call_args = Command._call_args.copy() # aggregate any 'with' contexts for prepend in get_prepend_stack(): pcall_args = prepend.call_args.copy() # don't pass the 'with' call arg pcall_args.pop("with", None) call_args.update(pcall_args) cmd.extend(prepend.cmd) cmd.append(self._path) # do we have an argument pre-processor? if so, run it. we need to do # this early, so that args, kwargs are accurate preprocessor = self._partial_call_args.get("arg_preprocess", None) if preprocessor: args, kwargs = preprocessor(args, kwargs) # here we extract the special kwargs and override any # special kwargs from the possibly baked command extracted_call_args, kwargs = self._extract_call_args(kwargs) call_args.update(self._partial_call_args) call_args.update(extracted_call_args) # handle a None. this is added back only to not break the api in the # 1.* version. TODO remove this in 2.0, as "ok_code", if specified, # should always be a definitive value or list of values, and None is # ambiguous if call_args["ok_code"] is None: call_args["ok_code"] = 0 if not getattr(call_args["ok_code"], "__iter__", None): call_args["ok_code"] = [call_args["ok_code"]] # check if we're piping via composition stdin = call_args["in"] if args: first_arg = args.pop(0) if isinstance(first_arg, RunningCommand): if first_arg.call_args["piped"]: stdin = first_arg.process else: stdin = first_arg.process._pipe_queue else: args.insert(0, first_arg) processed_args = compile_args(args, kwargs, call_args["long_sep"], call_args["long_prefix"]) # makes sure our arguments are broken up correctly split_args = self._partial_baked_args + processed_args final_args = split_args cmd.extend(final_args) # if we're running in foreground mode, we need to completely bypass # launching a RunningCommand and OProc and just do a spawn if call_args["fg"]: if call_args["env"] is None: launch = lambda: os.spawnv(os.P_WAIT, cmd[0], cmd) else: launch = lambda: os.spawnve(os.P_WAIT, cmd[0], cmd, call_args["env"]) exit_code = launch() exc_class = get_exc_exit_code_would_raise(exit_code, call_args["ok_code"], call_args["piped"]) if exc_class: if IS_PY3: ran = " ".join([arg.decode(DEFAULT_ENCODING, "ignore") for arg in cmd]) else: ran = " ".join(cmd) exc = exc_class(ran, b"", b"", call_args["truncate_exc"]) raise exc return None # stdout redirection stdout = call_args["out"] if output_redirect_is_filename(stdout): stdout = open(str(stdout), "wb") # stderr redirection stderr = call_args["err"] if output_redirect_is_filename(stderr): stderr = open(str(stderr), "wb") return RunningCommand(cmd, call_args, stdin, stdout, stderr) def compile_args(args, kwargs, sep, prefix): """ takes args and kwargs, as they were passed into the command instance being executed with __call__, and compose them into a flat list that will eventually be fed into exec. example: with this call: sh.ls("-l", "/tmp", color="never") this function receives args = ['-l', '/tmp'] kwargs = {'color': 'never'} and produces ['-l', '/tmp', '--color=never'] """ processed_args = [] encode = encode_to_py3bytes_or_py2str # aggregate positional args for arg in args: if isinstance(arg, (list, tuple)): if isinstance(arg, GlobResults) and not arg: arg = [arg.path] for sub_arg in arg: processed_args.append(encode(sub_arg)) elif isinstance(arg, dict): processed_args += aggregate_keywords(arg, sep, prefix, raw=True) else: processed_args.append(encode(arg)) # aggregate the keyword arguments processed_args += aggregate_keywords(kwargs, sep, prefix) return processed_args def aggregate_keywords(keywords, sep, prefix, raw=False): """ take our keyword arguments, and a separator, and compose the list of flat long (and short) arguments. example {'color': 'never', 't': True, 'something': True} with sep '=' becomes ['--color=never', '-t', '--something'] the `raw` argument indicates whether or not we should leave the argument name alone, or whether we should replace "_" with "-". if we pass in a dictionary, like this: sh.command({"some_option": 12}) then `raw` gets set to True, because we want to leave the key as-is, to produce: ['--some_option=12'] but if we just use a command's kwargs, `raw` is False, which means this: sh.command(some_option=12) becomes: ['--some-option=12'] eessentially, using kwargs is a convenience, but it lacks the ability to put a '-' in the name, so we do the replacement of '_' to '-' for you. but when you really don't want that to happen, you should use a dictionary instead with the exact names you want """ processed = [] encode = encode_to_py3bytes_or_py2str for k, v in keywords.items(): # we're passing a short arg as a kwarg, example: # cut(d="\t") if len(k) == 1: if v is not False: processed.append(encode("-" + k)) if v is not True: processed.append(encode(v)) # we're doing a long arg else: if not raw: k = k.replace("_", "-") if v is True: processed.append(encode("--" + k)) elif v is False: pass elif sep is None or sep == " ": processed.append(encode(prefix + k)) processed.append(encode(v)) else: arg = encode("%s%s%s%s" % (prefix, k, sep, v)) processed.append(arg) return processed def _start_daemon_thread(fn, name, exc_queue, *args): def wrap(*args, **kwargs): try: fn(*args, **kwargs) except Exception as e: exc_queue.put(e) raise thrd = threading.Thread(target=wrap, name=name, args=args) thrd.daemon = True thrd.start() return thrd def setwinsize(fd, rows_cols): """ set the terminal size of a tty file descriptor. borrowed logic from pexpect.py """ rows, cols = rows_cols TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561) s = struct.pack('HHHH', rows, cols, 0, 0) fcntl.ioctl(fd, TIOCSWINSZ, s) def construct_streamreader_callback(process, handler): """ here we're constructing a closure for our streamreader callback. this is used in the case that we pass a callback into _out or _err, meaning we want to our callback to handle each bit of output we construct the closure based on how many arguments it takes. the reason for this is to make it as easy as possible for people to use, without limiting them. a new user will assume the callback takes 1 argument (the data). as they get more advanced, they may want to terminate the process, or pass some stdin back, and will realize that they can pass a callback of more args """ # implied arg refers to the "self" that methods will pass in. we need to # account for this implied arg when figuring out what function the user # passed in based on number of args implied_arg = 0 partial_args = 0 handler_to_inspect = handler if isinstance(handler, partial): partial_args = len(handler.args) handler_to_inspect = handler.func if inspect.ismethod(handler_to_inspect): implied_arg = 1 num_args = get_num_args(handler_to_inspect) else: if inspect.isfunction(handler_to_inspect): num_args = get_num_args(handler_to_inspect) # is an object instance with __call__ method else: implied_arg = 1 num_args = get_num_args(handler_to_inspect.__call__) net_args = num_args - implied_arg - partial_args handler_args = () # just the chunk if net_args == 1: handler_args = () # chunk, stdin if net_args == 2: handler_args = (process.stdin,) # chunk, stdin, process elif net_args == 3: # notice we're only storing a weakref, to prevent cyclic references # (where the process holds a streamreader, and a streamreader holds a # handler-closure with a reference to the process handler_args = (process.stdin, weakref.ref(process)) def fn(chunk): # this is pretty ugly, but we're evaluating the process at call-time, # because it's a weakref args = handler_args if len(args) == 2: args = (handler_args[0], handler_args[1]()) return handler(chunk, *args) return fn def get_exc_exit_code_would_raise(exit_code, ok_codes, sigpipe_ok): exc = None success = exit_code in ok_codes bad_sig = -exit_code in SIGNALS_THAT_SHOULD_THROW_EXCEPTION # if this is a piped command, SIGPIPE must be ignored by us and not raise an # exception, since it's perfectly normal for the consumer of a process's # pipe to terminate early if sigpipe_ok and -exit_code == signal.SIGPIPE: bad_sig = False success = True if not success or bad_sig: exc = get_rc_exc(exit_code) return exc def handle_process_exit_code(exit_code): """ this should only ever be called once for each child process """ # if we exited from a signal, let our exit code reflect that if os.WIFSIGNALED(exit_code): exit_code = -os.WTERMSIG(exit_code) # otherwise just give us a normal exit code elif os.WIFEXITED(exit_code): exit_code = os.WEXITSTATUS(exit_code) else: raise RuntimeError("Unknown child exit status!") return exit_code def no_interrupt(syscall, *args, **kwargs): """ a helper for making system calls immune to EINTR """ ret = None while True: try: ret = syscall(*args, **kwargs) except OSError as e: if e.errno == errno.EINTR: continue else: raise else: break return ret class OProc(object): """ this class is instantiated by RunningCommand for a command to be exec'd. it handles all the nasty business involved with correctly setting up the input/output to the child process. it gets its name for subprocess.Popen (process open) but we're calling ours OProc (open process) """ _default_window_size = (24, 80) # used in redirecting STDOUT = -1 STDERR = -2 def __init__(self, command, parent_log, cmd, stdin, stdout, stderr, call_args, pipe, process_assign_lock): """ cmd is the full string that will be exec'd. it includes the program name and all its arguments stdin, stdout, stderr are what the child will use for standard input/output/err call_args is a mapping of all the special keyword arguments to apply to the child process """ self.command = command self.call_args = call_args # convenience ca = self.call_args if ca["uid"] is not None: if os.getuid() != 0: raise RuntimeError("UID setting requires root privileges") target_uid = ca["uid"] pwrec = pwd.getpwuid(ca["uid"]) target_gid = pwrec.pw_gid # I had issues with getting 'Input/Output error reading stdin' from dd, # until I set _tty_out=False if ca["piped"]: ca["tty_out"] = False self._stdin_process = None # if the objects that we are passing to the OProc happen to be a # file-like object that is a tty, for example `sys.stdin`, then, later # on in this constructor, we're going to skip out on setting up pipes # and pseudoterminals for those endpoints stdin_is_tty_or_pipe = ob_is_tty(stdin) or ob_is_pipe(stdin) stdout_is_tty_or_pipe = ob_is_tty(stdout) or ob_is_pipe(stdout) stderr_is_tty_or_pipe = ob_is_tty(stderr) or ob_is_pipe(stderr) tee_out = ca["tee"] in (True, "out") tee_err = ca["tee"] == "err" # if we're passing in a custom stdout/out/err value, we obviously have # to force not using single_tty custom_in_out_err = stdin or stdout or stderr single_tty = (ca["tty_in"] and ca["tty_out"])\ and not custom_in_out_err # this logic is a little convoluted, but basically this top-level # if/else is for consolidating input and output TTYs into a single # TTY. this is the only way some secure programs like ssh will # output correctly (is if stdout and stdin are both the same TTY) if single_tty: self._stdin_read_fd, self._stdin_write_fd = pty.openpty() self._stdout_read_fd = os.dup(self._stdin_read_fd) self._stdout_write_fd = os.dup(self._stdin_write_fd) self._stderr_read_fd = os.dup(self._stdin_read_fd) self._stderr_write_fd = os.dup(self._stdin_write_fd) # do not consolidate stdin and stdout. this is the most common use- # case else: # this check here is because we may be doing piping and so our stdin # might be an instance of OProc if isinstance(stdin, OProc) and stdin.call_args["piped"]: self._stdin_write_fd = stdin._pipe_fd self._stdin_read_fd = None self._stdin_process = stdin elif stdin_is_tty_or_pipe: self._stdin_write_fd = os.dup(get_fileno(stdin)) self._stdin_read_fd = None elif ca["tty_in"]: self._stdin_read_fd, self._stdin_write_fd = pty.openpty() # tty_in=False is the default else: self._stdin_write_fd, self._stdin_read_fd = os.pipe() if stdout_is_tty_or_pipe and not tee_out: self._stdout_write_fd = os.dup(get_fileno(stdout)) self._stdout_read_fd = None # tty_out=True is the default elif ca["tty_out"]: self._stdout_read_fd, self._stdout_write_fd = pty.openpty() else: self._stdout_read_fd, self._stdout_write_fd = os.pipe() # unless STDERR is going to STDOUT, it ALWAYS needs to be a pipe, # and never a PTY. the reason for this is not totally clear to me, # but it has to do with the fact that if STDERR isn't set as the # CTTY (because STDOUT is), the STDERR buffer won't always flush # by the time the process exits, and the data will be lost. # i've only seen this on OSX. if stderr is OProc.STDOUT: # if stderr is going to stdout, but stdout is a tty or a pipe, # we should not specify a read_fd, because stdout is dup'd # directly to the stdout fd (no pipe), and so stderr won't have # a slave end of a pipe either to dup if stdout_is_tty_or_pipe and not tee_out: self._stderr_read_fd = None else: self._stderr_read_fd = os.dup(self._stdout_read_fd) self._stderr_write_fd = os.dup(self._stdout_write_fd) elif stderr_is_tty_or_pipe and not tee_err: self._stderr_write_fd = os.dup(get_fileno(stderr)) self._stderr_read_fd = None else: self._stderr_read_fd, self._stderr_write_fd = os.pipe() piped = ca["piped"] self._pipe_fd = None if piped: fd_to_use = self._stdout_read_fd if piped == "err": fd_to_use = self._stderr_read_fd self._pipe_fd = os.dup(fd_to_use) new_session = ca["new_session"] needs_ctty = ca["tty_in"] and new_session self.ctty = None if needs_ctty: self.ctty = os.ttyname(self._stdin_write_fd) # this is a hack, but what we're doing here is intentionally throwing an # OSError exception if our child processes's directory doesn't exist, # but we're doing it BEFORE we fork. the reason for before the fork is # error handling. i'm currently too lazy to implement what # subprocess.py did and set up a error pipe to handle exceptions that # happen in the child between fork and exec. it has only been seen in # the wild for a missing cwd, so we'll handle it here. cwd = ca["cwd"] if cwd is not None and not os.path.exists(cwd): os.chdir(cwd) gc_enabled = gc.isenabled() if gc_enabled: gc.disable() # for synchronizing session_pipe_read, session_pipe_write = os.pipe() exc_pipe_read, exc_pipe_write = os.pipe() # this pipe is for synchronzing with the child that the parent has # closed its in/out/err fds. this is a bug on OSX (but not linux), # where we can lose output sometimes, due to a race, if we do # os.close(self._stdout_write_fd) in the parent after the child starts # writing. if IS_OSX: close_pipe_read, close_pipe_write = os.pipe() # session id, group id, process id self.sid = None self.pgid = None self.pid = os.fork() # child if self.pid == 0: # pragma: no cover if IS_OSX: os.read(close_pipe_read, 1) os.close(close_pipe_read) os.close(close_pipe_write) try: # ignoring SIGHUP lets us persist even after the parent process # exits. only ignore if we're backgrounded if ca["bg"] is True: signal.signal(signal.SIGHUP, signal.SIG_IGN) # python ignores SIGPIPE by default. we must make sure to put # this behavior back to the default for spawned processes, # otherwise SIGPIPE won't kill piped processes, which is what we # need, so that we can check the error code of the killed # process to see that SIGPIPE killed it signal.signal(signal.SIGPIPE, signal.SIG_DFL) # put our forked process in a new session? this will relinquish # any control of our inherited CTTY and also make our parent # process init if new_session: os.setsid() # if we're not going in a new session, we should go in a new # process group. this way, our process, and any children it # spawns, are alone, contained entirely in one group. if we # didn't do this, and didn't use a new session, then our exec'd # process *could* exist in the same group as our python process, # depending on how we launch the process (from a shell, or some # other way) else: os.setpgrp() sid = os.getsid(0) pgid = os.getpgid(0) payload = ("%d,%d" % (sid, pgid)).encode(DEFAULT_ENCODING) os.write(session_pipe_write, payload) if ca["tty_out"] and not stdout_is_tty_or_pipe and not single_tty: # set raw mode, so there isn't any weird translation of # newlines to \r\n and other oddities. we're not outputting # to a terminal anyways # # we HAVE to do this here, and not in the parent process, # because we have to guarantee that this is set before the # child process is run, and we can't do it twice. tty.setraw(self._stdout_write_fd) # if the parent-side fd for stdin exists, close it. the case # where it may not exist is if we're using piping if self._stdin_read_fd: os.close(self._stdin_read_fd) if self._stdout_read_fd: os.close(self._stdout_read_fd) if self._stderr_read_fd: os.close(self._stderr_read_fd) os.close(session_pipe_read) os.close(exc_pipe_read) if cwd: os.chdir(cwd) os.dup2(self._stdin_write_fd, 0) os.dup2(self._stdout_write_fd, 1) os.dup2(self._stderr_write_fd, 2) # set our controlling terminal, but only if we're using a tty # for stdin. it doesn't make sense to have a ctty otherwise if needs_ctty: tmp_fd = os.open(os.ttyname(0), os.O_RDWR) os.close(tmp_fd) if ca["tty_out"] and not stdout_is_tty_or_pipe: setwinsize(1, ca["tty_size"]) if ca["uid"] is not None: os.setgid(target_gid) os.setuid(target_uid) preexec_fn = ca["preexec_fn"] if callable(preexec_fn): preexec_fn() # don't inherit file descriptors max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0] os.closerange(3, max_fd) # actually execute the process if ca["env"] is None: os.execv(cmd[0], cmd) else: os.execve(cmd[0], cmd, ca["env"]) # we must ensure that we carefully exit the child process on # exception, otherwise the parent process code will be executed # twice on exception https://github.com/amoffat/sh/issues/202 # # if your parent process experiences an exit code 255, it is most # likely that an exception occurred between the fork of the child # and the exec. this should be reported. except: # some helpful debugging try: tb = traceback.format_exc().encode("utf8", "ignore") os.write(exc_pipe_write, tb) finally: os._exit(255) # parent else: if gc_enabled: gc.enable() os.close(self._stdin_write_fd) os.close(self._stdout_write_fd) os.close(self._stderr_write_fd) # tell our child process that we've closed our write_fds, so it is # ok to proceed towards exec. see the comment where this pipe is # opened, for why this is necessary if IS_OSX: os.close(close_pipe_read) os.write(close_pipe_write, str(1).encode(DEFAULT_ENCODING)) os.close(close_pipe_write) os.close(exc_pipe_write) fork_exc = os.read(exc_pipe_read, 1024**2) os.close(exc_pipe_read) if fork_exc: fork_exc = fork_exc.decode(DEFAULT_ENCODING) raise ForkException(fork_exc) os.close(session_pipe_write) sid, pgid = os.read(session_pipe_read, 1024).decode(DEFAULT_ENCODING).split(",") os.close(session_pipe_read) self.sid = int(sid) self.pgid = int(pgid) # used to determine what exception to raise. if our process was # killed via a timeout counter, we'll raise something different than # a SIGKILL exception self.timed_out = False self.started = time.time() self.cmd = cmd # exit code should only be manipulated from within self._wait_lock # to prevent race conditions self.exit_code = None self.stdin = stdin or Queue() # _pipe_queue is used internally to hand off stdout from one process # to another. by default, all stdout from a process gets dumped # into this pipe queue, to be consumed in real time (hence the # thread-safe Queue), or at a potentially later time self._pipe_queue = Queue() # this is used to prevent a race condition when we're waiting for # a process to end, and the OProc's internal threads are also checking # for the processes's end self._wait_lock = threading.Lock() # these are for aggregating the stdout and stderr. we use a deque # because we don't want to overflow self._stdout = deque(maxlen=ca["internal_bufsize"]) self._stderr = deque(maxlen=ca["internal_bufsize"]) if ca["tty_in"] and not stdin_is_tty_or_pipe: setwinsize(self._stdin_read_fd, ca["tty_size"]) self.log = parent_log.get_child("process", repr(self)) self.log.debug("started process") # disable echoing, but only if it's a tty that we created ourselves if ca["tty_in"] and not stdin_is_tty_or_pipe: attr = termios.tcgetattr(self._stdin_read_fd) attr[3] &= ~termios.ECHO termios.tcsetattr(self._stdin_read_fd, termios.TCSANOW, attr) # we're only going to create a stdin thread iff we have potential # for stdin to come in. this would be through a stdout callback or # through an object we've passed in for stdin potentially_has_input = callable(stdout) or stdin # this represents the connection from a Queue object (or whatever # we're using to feed STDIN) to the process's STDIN fd self._stdin_stream = None if self._stdin_read_fd and potentially_has_input: log = self.log.get_child("streamwriter", "stdin") self._stdin_stream = StreamWriter(log, self._stdin_read_fd, self.stdin, ca["in_bufsize"], ca["encoding"], ca["tty_in"]) stdout_pipe = None if pipe is OProc.STDOUT and not ca["no_pipe"]: stdout_pipe = self._pipe_queue # this represents the connection from a process's STDOUT fd to # wherever it has to go, sometimes a pipe Queue (that we will use # to pipe data to other processes), and also an internal deque # that we use to aggregate all the output save_stdout = not ca["no_out"] and \ (tee_out or stdout is None) pipe_out = ca["piped"] in ("out", True) pipe_err = ca["piped"] in ("err",) # if we're piping directly into another process's filedescriptor, we # bypass reading from the stdout stream altogether, because we've # already hooked up this processes's stdout fd to the other # processes's stdin fd self._stdout_stream = None if not pipe_out and self._stdout_read_fd: if callable(stdout): stdout = construct_streamreader_callback(self, stdout) self._stdout_stream = \ StreamReader( self.log.get_child("streamreader", "stdout"), self._stdout_read_fd, stdout, self._stdout, ca["out_bufsize"], ca["encoding"], ca["decode_errors"], stdout_pipe, save_data=save_stdout) elif self._stdout_read_fd: os.close(self._stdout_read_fd) # if stderr is going to one place (because it's grouped with stdout, # or we're dealing with a single tty), then we don't actually need a # stream reader for stderr, because we've already set one up for # stdout above self._stderr_stream = None if stderr is not OProc.STDOUT and not single_tty and not pipe_err \ and self._stderr_read_fd: stderr_pipe = None if pipe is OProc.STDERR and not ca["no_pipe"]: stderr_pipe = self._pipe_queue save_stderr = not ca["no_err"] and \ (ca["tee"] in ("err",) or stderr is None) if callable(stderr): stderr = construct_streamreader_callback(self, stderr) self._stderr_stream = StreamReader(Logger("streamreader"), self._stderr_read_fd, stderr, self._stderr, ca["err_bufsize"], ca["encoding"], ca["decode_errors"], stderr_pipe, save_data=save_stderr) elif self._stderr_read_fd: os.close(self._stderr_read_fd) def timeout_fn(): self.timed_out = True self.signal(ca["timeout_signal"]) self._timeout_event = None self._timeout_timer = None if ca["timeout"]: self._timeout_event = threading.Event() self._timeout_timer = threading.Timer(ca["timeout"], self._timeout_event.set) self._timeout_timer.start() # this is for cases where we know that the RunningCommand that was # launched was not .wait()ed on to complete. in those unique cases, # we allow the thread that processes output to report exceptions in # that thread. it's important that we only allow reporting of the # exception, and nothing else (like the additional stuff that # RunningCommand.wait() does), because we want the exception to be # re-raised in the future, if we DO call .wait() handle_exit_code = None if not self.command._spawned_and_waited and ca["bg_exc"]: def fn(exit_code): with process_assign_lock: return self.command.handle_command_exit_code(exit_code) handle_exit_code = fn self._quit_threads = threading.Event() thread_name = "background thread for pid %d" % self.pid self._bg_thread_exc_queue = Queue(1) self._background_thread = _start_daemon_thread(background_thread, thread_name, self._bg_thread_exc_queue, timeout_fn, self._timeout_event, handle_exit_code, self.is_alive, self._quit_threads) # start the main io threads. stdin thread is not needed if we are # connecting from another process's stdout pipe self._input_thread = None self._input_thread_exc_queue = Queue(1) if self._stdin_stream: close_before_term = not needs_ctty thread_name = "STDIN thread for pid %d" % self.pid self._input_thread = _start_daemon_thread(input_thread, thread_name, self._input_thread_exc_queue, self.log, self._stdin_stream, self.is_alive, self._quit_threads, close_before_term) # this event is for cases where the subprocess that we launch # launches its OWN subprocess and dups the stdout/stderr fds to that # new subprocess. in that case, stdout and stderr will never EOF, # so our output_thread will never finish and will hang. this event # prevents that hanging self._stop_output_event = threading.Event() self._output_thread_exc_queue = Queue(1) thread_name = "STDOUT/ERR thread for pid %d" % self.pid self._output_thread = _start_daemon_thread(output_thread, thread_name, self._output_thread_exc_queue, self.log, self._stdout_stream, self._stderr_stream, self._timeout_event, self.is_alive, self._quit_threads, self._stop_output_event) def __repr__(self): return "" % (self.pid, self.cmd[:500]) # these next 3 properties are primary for tests @property def output_thread_exc(self): exc = None try: exc = self._output_thread_exc_queue.get(False) except Empty: pass return exc @property def input_thread_exc(self): exc = None try: exc = self._input_thread_exc_queue.get(False) except Empty: pass return exc @property def bg_thread_exc(self): exc = None try: exc = self._bg_thread_exc_queue.get(False) except Empty: pass return exc def change_in_bufsize(self, buf): self._stdin_stream.stream_bufferer.change_buffering(buf) def change_out_bufsize(self, buf): self._stdout_stream.stream_bufferer.change_buffering(buf) def change_err_bufsize(self, buf): self._stderr_stream.stream_bufferer.change_buffering(buf) @property def stdout(self): return "".encode(self.call_args["encoding"]).join(self._stdout) @property def stderr(self): return "".encode(self.call_args["encoding"]).join(self._stderr) def get_pgid(self): """ return the CURRENT group id of the process. this differs from self.pgid in that this refects the current state of the process, where self.pgid is the group id at launch """ return os.getpgid(self.pid) def get_sid(self): """ return the CURRENT session id of the process. this differs from self.sid in that this refects the current state of the process, where self.sid is the session id at launch """ return os.getsid(self.pid) def signal_group(self, sig): self.log.debug("sending signal %d to group", sig) os.killpg(self.get_pgid(), sig) def signal(self, sig): self.log.debug("sending signal %d", sig) os.kill(self.pid, sig) def kill_group(self): self.log.debug("killing group") self.signal_group(signal.SIGKILL) def kill(self): self.log.debug("killing") self.signal(signal.SIGKILL) def terminate(self): self.log.debug("terminating") self.signal(signal.SIGTERM) def is_alive(self): """ polls if our child process has completed, without blocking. this method has side-effects, such as setting our exit_code, if we happen to see our child exit while this is running """ if self.exit_code is not None: return False, self.exit_code # what we're doing here essentially is making sure that the main thread # (or another thread), isn't calling .wait() on the process. because # .wait() calls os.waitpid(self.pid, 0), we can't do an os.waitpid # here...because if we did, and the process exited while in this # thread, the main thread's os.waitpid(self.pid, 0) would raise OSError # (because the process ended in another thread). # # so essentially what we're doing is, using this lock, checking if # we're calling .wait(), and if we are, let .wait() get the exit code # and handle the status, otherwise let us do it. acquired = self._wait_lock.acquire(False) if not acquired: if self.exit_code is not None: return False, self.exit_code return True, self.exit_code try: # WNOHANG is just that...we're calling waitpid without hanging... # essentially polling the process. the return result is (0, 0) if # there's no process status, so we check that pid == self.pid below # in order to determine how to proceed pid, exit_code = no_interrupt(os.waitpid, self.pid, os.WNOHANG) if pid == self.pid: self.exit_code = handle_process_exit_code(exit_code) self._process_just_ended() return False, self.exit_code # no child process except OSError: return False, self.exit_code else: return True, self.exit_code finally: self._wait_lock.release() def _process_just_ended(self): if self._timeout_timer: self._timeout_timer.cancel() done_callback = self.call_args["done"] if done_callback: success = self.exit_code in self.call_args["ok_code"] done_callback(success, self.exit_code) # this can only be closed at the end of the process, because it might be # the CTTY, and closing it prematurely will send a SIGHUP. we also # don't want to close it if there's a self._stdin_stream, because that # is in charge of closing it also if self._stdin_read_fd and not self._stdin_stream: os.close(self._stdin_read_fd) def wait(self): """ waits for the process to complete, handles the exit code """ self.log.debug("acquiring wait lock to wait for completion") # using the lock in a with-context blocks, which is what we want if # we're running wait() with self._wait_lock: self.log.debug("got wait lock") witnessed_end = False if self.exit_code is None: self.log.debug("exit code not set, waiting on pid") pid, exit_code = no_interrupt(os.waitpid, self.pid, 0) # blocks self.exit_code = handle_process_exit_code(exit_code) witnessed_end = True else: self.log.debug("exit code already set (%d), no need to wait", self.exit_code) self._quit_threads.set() # we may not have a thread for stdin, if the pipe has been connected # via _piped="direct" if self._input_thread: self._input_thread.join() # wait, then signal to our output thread that the child process is # done, and we should have finished reading all the stdout/stderr # data that we can by now timer = threading.Timer(2.0, self._stop_output_event.set) timer.start() # wait for our stdout and stderr streamreaders to finish reading and # aggregating the process output self._output_thread.join() timer.cancel() self._background_thread.join() if witnessed_end: self._process_just_ended() return self.exit_code def input_thread(log, stdin, is_alive, quit, close_before_term): """ this is run in a separate thread. it writes into our process's stdin (a streamwriter) and waits the process to end AND everything that can be written to be written """ done = False closed = False alive = True poller = Poller() poller.register_write(stdin) while poller and alive: changed = poller.poll(1) for fd, events in changed: if events & (POLLER_EVENT_WRITE | POLLER_EVENT_HUP): log.debug("%r ready for more input", stdin) done = stdin.write() if done: poller.unregister(stdin) if close_before_term: stdin.close() closed = True alive, _ = is_alive() while alive: quit.wait(1) alive, _ = is_alive() if not closed: stdin.close() def event_wait(ev, timeout=None): triggered = ev.wait(timeout) if IS_PY26: triggered = ev.is_set() return triggered def background_thread(timeout_fn, timeout_event, handle_exit_code, is_alive, quit): """ handles the timeout logic """ # if there's a timeout event, loop if timeout_event: while not quit.is_set(): timed_out = event_wait(timeout_event, 0.1) if timed_out: timeout_fn() break # handle_exit_code will be a function ONLY if our command was NOT waited on # as part of its spawning. in other words, it's probably a background # command # # this reports the exit code exception in our thread. it's purely for the # user's awareness, and cannot be caught or used in any way, so it's ok to # suppress this during the tests if handle_exit_code and not RUNNING_TESTS: # pragma: no cover alive = True while alive: quit.wait(1) alive, exit_code = is_alive() handle_exit_code(exit_code) def output_thread(log, stdout, stderr, timeout_event, is_alive, quit, stop_output_event): """ this function is run in a separate thread. it reads from the process's stdout stream (a streamreader), and waits for it to claim that its done """ poller = Poller() if stdout is not None: poller.register_read(stdout) if stderr is not None: poller.register_read(stderr) # this is our poll loop for polling stdout or stderr that is ready to # be read and processed. if one of those streamreaders indicate that it # is done altogether being read from, we remove it from our list of # things to poll. when no more things are left to poll, we leave this # loop and clean up while poller: changed = no_interrupt(poller.poll, 0.1) for f, events in changed: if events & (POLLER_EVENT_READ | POLLER_EVENT_HUP): log.debug("%r ready to be read from", f) done = f.read() if done: poller.unregister(f) elif events & POLLER_EVENT_ERROR: # for some reason, we have to just ignore streams that have had an # error. i'm not exactly sure why, but don't remove this until we # figure that out, and create a test for it pass if timeout_event and timeout_event.is_set(): break if stop_output_event.is_set(): break # we need to wait until the process is guaranteed dead before closing our # outputs, otherwise SIGPIPE alive, _ = is_alive() while alive: quit.wait(1) alive, _ = is_alive() if stdout: stdout.close() if stderr: stderr.close() class DoneReadingForever(Exception): pass class NotYetReadyToRead(Exception): pass def determine_how_to_read_input(input_obj): """ given some kind of input object, return a function that knows how to read chunks of that input object. each reader function should return a chunk and raise a DoneReadingForever exception, or return None, when there's no more data to read NOTE: the function returned does not need to care much about the requested buffering type (eg, unbuffered vs newline-buffered). the StreamBufferer will take care of that. these functions just need to return a reasonably-sized chunk of data. """ get_chunk = None if isinstance(input_obj, Queue): log_msg = "queue" get_chunk = get_queue_chunk_reader(input_obj) elif callable(input_obj): log_msg = "callable" get_chunk = get_callable_chunk_reader(input_obj) # also handles stringio elif hasattr(input_obj, "read"): log_msg = "file descriptor" get_chunk = get_file_chunk_reader(input_obj) elif isinstance(input_obj, basestring): log_msg = "string" get_chunk = get_iter_string_reader(input_obj) elif isinstance(input_obj, bytes): log_msg = "bytes" get_chunk = get_iter_string_reader(input_obj) elif isinstance(input_obj, GeneratorType): log_msg = "generator" get_chunk = get_iter_chunk_reader(iter(input_obj)) else: try: it = iter(input_obj) except TypeError: raise Exception("unknown input object") else: log_msg = "general iterable" get_chunk = get_iter_chunk_reader(it) return get_chunk, log_msg def get_queue_chunk_reader(stdin): def fn(): try: chunk = stdin.get(True, 0.1) except Empty: raise NotYetReadyToRead if chunk is None: raise DoneReadingForever return chunk return fn def get_callable_chunk_reader(stdin): def fn(): try: data = stdin() except DoneReadingForever: raise if not data: raise DoneReadingForever return data return fn def get_iter_string_reader(stdin): """ return an iterator that returns a chunk of a string every time it is called. notice that even though bufsize_type might be line buffered, we're not doing any line buffering here. that's because our StreamBufferer handles all buffering. we just need to return a reasonable-sized chunk. """ bufsize = 1024 iter_str = (stdin[i:i + bufsize] for i in range(0, len(stdin), bufsize)) return get_iter_chunk_reader(iter_str) def get_iter_chunk_reader(stdin): def fn(): try: if IS_PY3: chunk = stdin.__next__() else: chunk = stdin.next() return chunk except StopIteration: raise DoneReadingForever return fn def get_file_chunk_reader(stdin): bufsize = 1024 def fn(): # python 3.* includes a fileno on stringios, but accessing it throws an # exception. that exception is how we'll know we can't do a poll on # stdin is_real_file = True if IS_PY3: try: stdin.fileno() except UnsupportedOperation: is_real_file = False # this poll is for files that may not yet be ready to read. we test # for fileno because StringIO/BytesIO cannot be used in a poll if is_real_file and hasattr(stdin, "fileno"): poller = Poller() poller.register_read(stdin) changed = poller.poll(0.1) ready = False for fd, events in changed: if events & (POLLER_EVENT_READ | POLLER_EVENT_HUP): ready = True if not ready: raise NotYetReadyToRead chunk = stdin.read(bufsize) if not chunk: raise DoneReadingForever else: return chunk return fn def bufsize_type_to_bufsize(bf_type): """ for a given bufsize type, return the actual bufsize we will read. notice that although 1 means "newline-buffered", we're reading a chunk size of 1024. this is because we have to read something. we let a StreamBufferer instance handle splitting our chunk on newlines """ # newlines if bf_type == 1: bufsize = 1024 # unbuffered elif bf_type == 0: bufsize = 1 # or buffered by specific amount else: bufsize = bf_type return bufsize class StreamWriter(object): """ StreamWriter reads from some input (the stdin param) and writes to a fd (the stream param). the stdin may be a Queue, a callable, something with the "read" method, a string, or an iterable """ def __init__(self, log, stream, stdin, bufsize_type, encoding, tty_in): self.stream = stream self.stdin = stdin self.log = log self.encoding = encoding self.tty_in = tty_in self.stream_bufferer = StreamBufferer(bufsize_type, self.encoding) self.get_chunk, log_msg = determine_how_to_read_input(stdin) self.log.debug("parsed stdin as a %s", log_msg) def fileno(self): """ defining this allows us to do poll on an instance of this class """ return self.stream def write(self): """ attempt to get a chunk of data to write to our child process's stdin, then write it. the return value answers the questions "are we done writing forever?" """ # get_chunk may sometimes return bytes, and sometimes return strings # because of the nature of the different types of STDIN objects we # support try: chunk = self.get_chunk() if chunk is None: raise DoneReadingForever except DoneReadingForever: self.log.debug("done reading") if self.tty_in: # EOF time try: char = termios.tcgetattr(self.stream)[6][termios.VEOF] except: char = chr(4).encode() # normally, one EOF should be enough to signal to an program # that is read()ing, to return 0 and be on your way. however, # some programs are misbehaved, like python3.1 and python3.2. # they don't stop reading sometimes after read() returns 0. # this can be demonstrated with the following program: # # import sys # sys.stdout.write(sys.stdin.read()) # # then type 'a' followed by ctrl-d 3 times. in python # 2.6,2.7,3.3,3.4,3.5,3.6, it only takes 2 ctrl-d to terminate. # however, in python 3.1 and 3.2, it takes all 3. # # so here we send an extra EOF along, just in case. i don't # believe it can hurt anything os.write(self.stream, char) os.write(self.stream, char) return True except NotYetReadyToRead: self.log.debug("received no data") return False # if we're not bytes, make us bytes if IS_PY3 and hasattr(chunk, "encode"): chunk = chunk.encode(self.encoding) for proc_chunk in self.stream_bufferer.process(chunk): self.log.debug("got chunk size %d: %r", len(proc_chunk), proc_chunk[:30]) self.log.debug("writing chunk to process") try: os.write(self.stream, proc_chunk) except OSError: self.log.debug("OSError writing stdin chunk") return True def close(self): self.log.debug("closing, but flushing first") chunk = self.stream_bufferer.flush() self.log.debug("got chunk size %d to flush: %r", len(chunk), chunk[:30]) try: if chunk: os.write(self.stream, chunk) except OSError: pass os.close(self.stream) def determine_how_to_feed_output(handler, encoding, decode_errors): if callable(handler): process, finish = get_callback_chunk_consumer(handler, encoding, decode_errors) # in py3, this is used for bytes elif isinstance(handler, (cStringIO, iocStringIO)): process, finish = get_cstringio_chunk_consumer(handler) # in py3, this is used for unicode elif isinstance(handler, (StringIO, ioStringIO)): process, finish = get_stringio_chunk_consumer(handler, encoding, decode_errors) elif hasattr(handler, "write"): process, finish = get_file_chunk_consumer(handler) else: try: handler = int(handler) except (ValueError, TypeError): process = lambda chunk: False finish = lambda: None else: process, finish = get_fd_chunk_consumer(handler) return process, finish def get_fd_chunk_consumer(handler): handler = fdopen(handler, "w", closefd=False) return get_file_chunk_consumer(handler) def get_file_chunk_consumer(handler): encode = lambda chunk: chunk if getattr(handler, "encoding", None): encode = lambda chunk: chunk.decode(handler.encoding) flush = lambda: None if hasattr(handler, "flush"): flush = handler.flush def process(chunk): handler.write(encode(chunk)) # we should flush on an fd. chunk is already the correctly-buffered # size, so we don't need the fd buffering as well flush() return False def finish(): flush() return process, finish def get_callback_chunk_consumer(handler, encoding, decode_errors): def process(chunk): # try to use the encoding first, if that doesn't work, send # the bytes, because it might be binary try: chunk = chunk.decode(encoding, decode_errors) except UnicodeDecodeError: pass return handler(chunk) def finish(): pass return process, finish def get_cstringio_chunk_consumer(handler): def process(chunk): handler.write(chunk) return False def finish(): pass return process, finish def get_stringio_chunk_consumer(handler, encoding, decode_errors): def process(chunk): handler.write(chunk.decode(encoding, decode_errors)) return False def finish(): pass return process, finish class StreamReader(object): """ reads from some output (the stream) and sends what it just read to the handler. """ def __init__(self, log, stream, handler, buffer, bufsize_type, encoding, decode_errors, pipe_queue=None, save_data=True): self.stream = stream self.buffer = buffer self.save_data = save_data self.encoding = encoding self.decode_errors = decode_errors self.pipe_queue = None if pipe_queue: self.pipe_queue = weakref.ref(pipe_queue) self.log = log self.stream_bufferer = StreamBufferer(bufsize_type, self.encoding, self.decode_errors) self.bufsize = bufsize_type_to_bufsize(bufsize_type) self.process_chunk, self.finish_chunk_processor = \ determine_how_to_feed_output(handler, encoding, decode_errors) self.should_quit = False def fileno(self): """ defining this allows us to do poll on an instance of this class """ return self.stream def close(self): chunk = self.stream_bufferer.flush() self.log.debug("got chunk size %d to flush: %r", len(chunk), chunk[:30]) if chunk: self.write_chunk(chunk) self.finish_chunk_processor() if self.pipe_queue and self.save_data: self.pipe_queue().put(None) os.close(self.stream) def write_chunk(self, chunk): # in PY3, the chunk coming in will be bytes, so keep that in mind if not self.should_quit: self.should_quit = self.process_chunk(chunk) if self.save_data: self.buffer.append(chunk) if self.pipe_queue: self.log.debug("putting chunk onto pipe: %r", chunk[:30]) self.pipe_queue().put(chunk) def read(self): # if we're PY3, we're reading bytes, otherwise we're reading # str try: chunk = no_interrupt(os.read, self.stream, self.bufsize) except OSError as e: self.log.debug("got errno %d, done reading", e.errno) return True if not chunk: self.log.debug("got no chunk, done reading") return True self.log.debug("got chunk size %d: %r", len(chunk), chunk[:30]) for chunk in self.stream_bufferer.process(chunk): self.write_chunk(chunk) class StreamBufferer(object): """ this is used for feeding in chunks of stdout/stderr, and breaking it up into chunks that will actually be put into the internal buffers. for example, if you have two processes, one being piped to the other, and you want that, first process to feed lines of data (instead of the chunks however they come in), OProc will use an instance of this class to chop up the data and feed it as lines to be sent down the pipe """ def __init__(self, buffer_type, encoding=DEFAULT_ENCODING, decode_errors="strict"): # 0 for unbuffered, 1 for line, everything else for that amount self.type = buffer_type self.buffer = [] self.n_buffer_count = 0 self.encoding = encoding self.decode_errors = decode_errors # this is for if we change buffering types. if we change from line # buffered to unbuffered, its very possible that our self.buffer list # has data that was being saved up (while we searched for a newline). # we need to use that up, so we don't lose it self._use_up_buffer_first = False # the buffering lock is used because we might change the buffering # types from a different thread. for example, if we have a stdout # callback, we might use it to change the way stdin buffers. so we # lock self._buffering_lock = threading.RLock() self.log = Logger("stream_bufferer") def change_buffering(self, new_type): # TODO, when we stop supporting 2.6, make this a with context self.log.debug("acquiring buffering lock for changing buffering") self._buffering_lock.acquire() self.log.debug("got buffering lock for changing buffering") try: if new_type == 0: self._use_up_buffer_first = True self.type = new_type finally: self._buffering_lock.release() self.log.debug("released buffering lock for changing buffering") def process(self, chunk): # MAKE SURE THAT THE INPUT IS PY3 BYTES # THE OUTPUT IS ALWAYS PY3 BYTES # TODO, when we stop supporting 2.6, make this a with context self.log.debug("acquiring buffering lock to process chunk (buffering: %d)", self.type) self._buffering_lock.acquire() self.log.debug("got buffering lock to process chunk (buffering: %d)", self.type) try: # unbuffered if self.type == 0: if self._use_up_buffer_first: self._use_up_buffer_first = False to_write = self.buffer self.buffer = [] to_write.append(chunk) return to_write return [chunk] # line buffered elif self.type == 1: total_to_write = [] nl = "\n".encode(self.encoding) while True: newline = chunk.find(nl) if newline == -1: break chunk_to_write = chunk[:newline + 1] if self.buffer: chunk_to_write = b"".join(self.buffer) + chunk_to_write self.buffer = [] self.n_buffer_count = 0 chunk = chunk[newline + 1:] total_to_write.append(chunk_to_write) if chunk: self.buffer.append(chunk) self.n_buffer_count += len(chunk) return total_to_write # N size buffered else: total_to_write = [] while True: overage = self.n_buffer_count + len(chunk) - self.type if overage >= 0: ret = "".encode(self.encoding).join(self.buffer) + chunk chunk_to_write = ret[:self.type] chunk = ret[self.type:] total_to_write.append(chunk_to_write) self.buffer = [] self.n_buffer_count = 0 else: self.buffer.append(chunk) self.n_buffer_count += len(chunk) break return total_to_write finally: self._buffering_lock.release() self.log.debug("released buffering lock for processing chunk (buffering: %d)", self.type) def flush(self): self.log.debug("acquiring buffering lock for flushing buffer") self._buffering_lock.acquire() self.log.debug("got buffering lock for flushing buffer") try: ret = "".encode(self.encoding).join(self.buffer) self.buffer = [] return ret finally: self._buffering_lock.release() self.log.debug("released buffering lock for flushing buffer") def with_lock(lock): def wrapped(fn): fn = contextmanager(fn) @contextmanager def wrapped2(*args, **kwargs): with lock: with fn(*args, **kwargs): yield return wrapped2 return wrapped @with_lock(PUSHD_LOCK) def pushd(path): """ pushd changes the actual working directory for the duration of the context, unlike the _cwd arg this will work with other built-ins such as sh.glob correctly """ orig_path = os.getcwd() os.chdir(path) try: yield finally: os.chdir(orig_path) @contextmanager def args(**kwargs): """ allows us to temporarily override all the special keyword parameters in a with context """ kwargs_str = ",".join(["%s=%r" % (k,v) for k,v in kwargs.items()]) raise DeprecationWarning(""" sh.args() has been deprecated because it was never thread safe. use the following instead: sh2 = sh({kwargs}) sh2.your_command() or sh2 = sh({kwargs}) from sh2 import your_command your_command() """.format(kwargs=kwargs_str)) class Environment(dict): """ this allows lookups to names that aren't found in the global scope to be searched for as a program name. for example, if "ls" isn't found in this module's scope, we consider it a system program and try to find it. we use a dict instead of just a regular object as the base class because the exec() statement used in the run_repl requires the "globals" argument to be a dictionary """ # this is a list of all of the names that the sh module exports that will # not resolve to functions. we don't want to accidentally shadow real # commands with functions/imports that we define in sh.py. for example, # "import time" may override the time system program whitelist = set([ "Command", "RunningCommand", "CommandNotFound", "DEFAULT_ENCODING", "DoneReadingForever", "ErrorReturnCode", "NotYetReadyToRead", "SignalException", "ForkException", "TimeoutException", "__project_url__", "__version__", "__file__", "args", "pushd", "glob", "contrib", ]) def __init__(self, globs, baked_args={}): """ baked_args are defaults for the 'sh' execution context. for example: tmp = sh(_out=StringIO()) 'out' would end up in here as an entry in the baked_args dict """ self.globs = globs self.baked_args = baked_args self.disable_whitelist = False def __getitem__(self, k): # if we first import "_disable_whitelist" from sh, we can import # anything defined in the global scope of sh.py. this is useful for our # tests if k == "_disable_whitelist": self.disable_whitelist = True return None # we're trying to import something real (maybe), see if it's in our # global scope if k in self.whitelist or self.disable_whitelist: return self.globs[k] # somebody tried to be funny and do "from sh import *" if k == "__all__": raise RuntimeError("Cannot import * from sh. \ Please import sh or import programs individually.") # check if we're naming a dynamically generated ReturnCode exception exc = get_exc_from_name(k) if exc: return exc # https://github.com/ipython/ipython/issues/2577 # https://github.com/amoffat/sh/issues/97#issuecomment-10610629 if k.startswith("__") and k.endswith("__"): raise AttributeError # is it a custom builtin? builtin = getattr(self, "b_" + k, None) if builtin: return builtin # is it a command? cmd = resolve_command(k, self.baked_args) if cmd: return cmd # how about an environment variable? # this check must come after testing if its a command, because on some # systems, there are an environment variables that can conflict with # command names. # https://github.com/amoffat/sh/issues/238 try: return os.environ[k] except KeyError: pass # nothing found, raise an exception raise CommandNotFound(k) # methods that begin with "b_" are custom builtins and will override any # program that exists in our path. this is useful for things like # common shell builtins that people are used to, but which aren't actually # full-fledged system binaries def b_cd(self, path=None): if path: os.chdir(path) else: os.chdir(os.path.expanduser('~')) def b_which(self, program, paths=None): return which(program, paths) class Contrib(ModuleType): # pragma: no cover @classmethod def __call__(cls, name): def wrapper1(fn): @property def cmd_getter(self): cmd = resolve_command(name) if not cmd: raise CommandNotFound(name) new_cmd = fn(cmd) return new_cmd setattr(cls, name, cmd_getter) return fn return wrapper1 mod_name = __name__ + ".contrib" contrib = Contrib(mod_name) sys.modules[mod_name] = contrib @contrib("git") def git(orig): # pragma: no cover """ most git commands play nicer without a TTY """ cmd = orig.bake(_tty_out=False) return cmd @contrib("sudo") def sudo(orig): # pragma: no cover """ a nicer version of sudo that uses getpass to ask for a password, or allows the first argument to be a string password """ prompt = "[sudo] password for %s: " % getpass.getuser() def stdin(): pw = getpass.getpass(prompt=prompt) + "\n" yield pw def process(args, kwargs): password = kwargs.pop("password", None) if password is None: pass_getter = stdin() else: pass_getter = password.rstrip("\n") + "\n" kwargs["_in"] = pass_getter return args, kwargs cmd = orig.bake("-S", _arg_preprocess=process) return cmd def run_repl(env): # pragma: no cover banner = "\n>> sh v{version}\n>> https://github.com/amoffat/sh\n" print(banner.format(version=__version__)) while True: try: line = raw_input("sh> ") except (ValueError, EOFError): break try: exec(compile(line, "", "single"), env, env) except SystemExit: break except: print(traceback.format_exc()) # cleans up our last line print("") # this is a thin wrapper around THIS module (we patch sys.modules[__name__]). # this is in the case that the user does a "from sh import whatever" # in other words, they only want to import certain programs, not the whole # system PATH worth of commands. in this case, we just proxy the # import lookup to our Environment class class SelfWrapper(ModuleType): def __init__(self, self_module, baked_args={}): # this is super ugly to have to copy attributes like this, # but it seems to be the only way to make reload() behave # nicely. if i make these attributes dynamic lookups in # __getattr__, reload sometimes chokes in weird ways... for attr in ["__builtins__", "__doc__", "__file__", "__name__", "__package__"]: setattr(self, attr, getattr(self_module, attr, None)) # python 3.2 (2.7 and 3.3 work fine) breaks on osx (not ubuntu) # if we set this to None. and 3.3 needs a value for __path__ self.__path__ = [] self.__self_module = self_module self.__env = Environment(globals(), baked_args=baked_args) def __getattr__(self, name): return self.__env[name] def __call__(self, **kwargs): """ returns a new SelfWrapper object, where all commands spawned from it have the baked_args kwargs set on them by default """ baked_args = self.__env.baked_args.copy() baked_args.update(kwargs) new_mod = self.__class__(self.__self_module, baked_args) # inspect the line in the parent frame that calls and assigns the new sh # variable, and get the name of the new variable we're assigning to. # this is very brittle and pretty much a sin. but it works in 99% of # the time and the tests pass # # the reason we need to do this is because we need to remove the old # cached module from sys.modules. if we don't, it gets re-used, and any # old baked params get used, which is not what we want parent = inspect.stack()[1] code = parent[4][0].strip() parsed = ast.parse(code) module_name = parsed.body[0].targets[0].id if module_name == __name__: raise RuntimeError("Cannot use the name 'sh' as an execution context") sys.modules.pop(module_name, None) return new_mod def in_importlib(frame): """ helper for checking if a filename is in importlib guts """ return frame.f_code.co_filename == "" def register_importer(): """ registers our fancy importer that can let us import from a module name, like: import sh tmp = sh() from tmp import ls """ def test(importer): return importer.__class__.__name__ == ModuleImporterFromVariables.__name__ already_registered = any([True for i in sys.meta_path if test(i)]) if not already_registered: importer = ModuleImporterFromVariables( restrict_to=["SelfWrapper"], ) sys.meta_path.insert(0, importer) return not already_registered def fetch_module_from_frame(name, frame): mod = frame.f_locals.get(name, frame.f_globals.get(name, None)) return mod class ModuleImporterFromVariables(object): """ a fancy importer that allows us to import from a variable that was recently set in either the local or global scope, like this: sh2 = sh(_timeout=3) from sh2 import ls """ def __init__(self, restrict_to=None): self.restrict_to = set(restrict_to or set()) def find_module(self, mod_fullname, path=None): """ mod_fullname doubles as the name of the VARIABLE holding our new sh context. for example: derp = sh() from derp import ls here, mod_fullname will be "derp". keep that in mind as we go throug the rest of this function """ parent_frame = inspect.currentframe().f_back while in_importlib(parent_frame): parent_frame = parent_frame.f_back # this line is saying "hey, does mod_fullname exist as a name we've # defind previously?" the purpose of this is to ensure that # mod_fullname is really a thing we've defined. if we haven't defined # it before, then we "can't" import from it module = fetch_module_from_frame(mod_fullname, parent_frame) if not module: return None # make sure it's a class we're allowed to import from if module.__class__.__name__ not in self.restrict_to: return None return self def load_module(self, mod_fullname): parent_frame = inspect.currentframe().f_back while in_importlib(parent_frame): parent_frame = parent_frame.f_back module = fetch_module_from_frame(mod_fullname, parent_frame) # we HAVE to include the module in sys.modules, per the import PEP. # older verions of python were more lenient about this being set, but # not in >= python3.3, unfortunately. this requirement necessitates the # ugly code in SelfWrapper.__call__ sys.modules[mod_fullname] = module module.__loader__ = self return module def run_tests(env, locale, args, version, force_select, **extra_env): # pragma: no cover py_version = "python" py_version += str(version) py_bin = which(py_version) return_code = None poller = "poll" if force_select: poller = "select" if py_bin: print("Testing %s, locale %r, poller: %s" % (py_version.capitalize(), locale, poller)) env["SH_TESTS_USE_SELECT"] = str(int(force_select)) env["LANG"] = locale for k,v in extra_env.items(): env[k] = str(v) cmd = [py_bin, "-W", "ignore", os.path.join(THIS_DIR, "test.py")] + args[1:] launch = lambda: os.spawnve(os.P_WAIT, cmd[0], cmd, env) return_code = launch() return return_code # we're being run as a stand-alone script if __name__ == "__main__": # pragma: no cover def parse_args(): from optparse import OptionParser parser = OptionParser() parser.add_option("-e", "--envs", dest="envs", action="append") parser.add_option("-l", "--locales", dest="constrain_locales", action="append") options, args = parser.parse_args() envs = options.envs or [] constrain_locales = options.constrain_locales or [] return args, envs, constrain_locales # these are essentially restrictions on what envs/constrain_locales to restrict to for # the tests. if they're empty lists, it means use all available args, constrain_versions, constrain_locales = parse_args() action = None if args: action = args[0] if action in ("test", "travis"): import test coverage = None if test.HAS_UNICODE_LITERAL: import coverage env = os.environ.copy() env["SH_TESTS_RUNNING"] = "1" if coverage: test.append_module_path(env, coverage) # if we're testing locally, run all versions of python on the system if action == "test": all_versions = ("2.6", "2.7", "3.1", "3.2", "3.3", "3.4", "3.5", "3.6") # if we're testing on travis, just use the system's default python, # since travis will spawn a vm per python version in our .travis.yml # file elif action == "travis": v = sys.version_info sys_ver = "%d.%d" % (v[0], v[1]) all_versions = (sys_ver,) all_force_select = [True] if HAS_POLL: all_force_select.append(False) all_locales = ("en_US.UTF-8", "C") i = 0 for locale in all_locales: if constrain_locales and locale not in constrain_locales: continue for version in all_versions: if constrain_versions and version not in constrain_versions: continue for force_select in all_force_select: env_copy = env.copy() exit_code = run_tests(env_copy, locale, args, version, force_select, SH_TEST_RUN_IDX=i) if exit_code is None: print("Couldn't find %s, skipping" % version) elif exit_code != 0: print("Failed for %s, %s" % (version, locale)) exit(1) i += 1 ran_versions = ",".join(all_versions) print("Tested Python versions: %s" % ran_versions) else: env = Environment(globals()) run_repl(env) # we're being imported from somewhere else: self = sys.modules[__name__] sys.modules[__name__] = SelfWrapper(self) register_importer() python-sh-1.12.14/test.py000066400000000000000000002334641334350127300151570ustar00rootroot00000000000000# -*- coding: utf8 -*- import sys import os IS_PY3 = sys.version_info[0] == 3 IS_PY2 = not IS_PY3 MINOR_VER = sys.version_info[1] # coverage doesn't work in python 3.1, 3.2 due to it just being a shit # python HAS_UNICODE_LITERAL = not (IS_PY3 and MINOR_VER in (1, 2)) cov = None if HAS_UNICODE_LITERAL: run_idx = int(os.environ.pop("SH_TEST_RUN_IDX", "0")) first_run = run_idx == 0 import coverage # for some reason, we can't run auto_data on the first run, or the coverage # numbers get really screwed up auto_data = True if first_run: auto_data = False cov = coverage.Coverage(auto_data=auto_data) if first_run: cov.erase() cov.start() from os.path import exists, join, realpath, dirname, split import unittest try: import unittest.mock except ImportError: HAS_MOCK = False else: HAS_MOCK = True import tempfile import warnings import pty import resource import logging import sys from contextlib import contextmanager import sh import signal import errno import stat import platform from functools import wraps import time import inspect # we have to use the real path because on osx, /tmp is a symlink to # /private/tmp, and so assertions that gettempdir() == sh.pwd() will fail tempdir = realpath(tempfile.gettempdir()) IS_OSX = platform.system() == "Darwin" # these 3 functions are helpers for modifying PYTHONPATH with a module's main # directory def append_pythonpath(env, path): key = "PYTHONPATH" pypath = [p for p in env.get(key, "").split(":") if p] pypath.insert(0, path) pypath = ":".join(pypath) env[key] = pypath def get_module_import_dir(m): mod_file = inspect.getsourcefile(m) is_package = mod_file.endswith("__init__.py") mod_dir = dirname(mod_file) if is_package: mod_dir, _ = split(mod_dir) return mod_dir def append_module_path(env, m): append_pythonpath(env, get_module_import_dir(m)) if IS_PY3: xrange = range unicode = str long = int from io import StringIO ioStringIO = StringIO from io import BytesIO as cStringIO iocStringIO = cStringIO python = sh.Command(sh.which("python%d.%d" % sys.version_info[:2])) else: from StringIO import StringIO from cStringIO import StringIO as cStringIO from io import StringIO as ioStringIO from io import BytesIO as iocStringIO python = sh.python THIS_DIR = dirname(os.path.abspath(__file__)) # this is to ensure that our `python` helper here is able to import our local sh # module, and not the system one baked_env = os.environ.copy() append_module_path(baked_env, sh) python = python.bake(_env=baked_env) if hasattr(logging, 'NullHandler'): NullHandler = logging.NullHandler else: class NullHandler(logging.Handler): def handle(self, record): pass def emit(self, record): pass def createLock(self): self.lock = None skipUnless = getattr(unittest, "skipUnless", None) if not skipUnless: # our stupid skipUnless wrapper for python2.6 def skipUnless(condition, reason): def wrapper(test): if condition: return test else: @wraps(test) def skip(*args, **kwargs): return return skip return wrapper skip_unless = skipUnless def requires_progs(*progs): missing = [] for prog in progs: try: sh.Command(prog) except sh.CommandNotFound: missing.append(prog) friendly_missing = ", ".join(missing) return skipUnless(len(missing) == 0, "Missing required system programs: %s" % friendly_missing) requires_posix = skipUnless(os.name == "posix", "Requires POSIX") requires_utf8 = skipUnless(sh.DEFAULT_ENCODING == "UTF-8", "System encoding must be UTF-8") not_osx = skipUnless(not IS_OSX, "Doesn't work on OSX") requires_py3 = skipUnless(IS_PY3, "Test only works on Python 3") requires_py35 = skipUnless(IS_PY3 and MINOR_VER >= 5, "Test only works on Python 3.5 or higher") def requires_poller(poller): use_select = bool(int(os.environ.get("SH_TESTS_USE_SELECT", "0"))) cur_poller = "select" if use_select else "poll" return skipUnless(cur_poller == poller, "Only enabled for select.%s" % cur_poller) @contextmanager def ulimit(key, new_soft): soft, hard = resource.getrlimit(key) resource.setrlimit(key, (new_soft, hard)) try: yield finally: resource.setrlimit(key, (soft, hard)) def create_tmp_test(code, prefix="tmp", delete=True, **kwargs): """ creates a temporary test file that lives on disk, on which we can run python with sh """ py = tempfile.NamedTemporaryFile(prefix=prefix, delete=delete) code = code.format(**kwargs) if IS_PY3: code = code.encode("UTF-8") py.write(code) py.flush() # make the file executable st = os.stat(py.name) os.chmod(py.name, st.st_mode | stat.S_IEXEC) # we don't explicitly close, because close will remove the file, and we # don't want that until the test case is done. so we let the gc close it # when it goes out of scope return py class BaseTests(unittest.TestCase): def assert_oserror(self, num, fn, *args, **kwargs): try: fn(*args, **kwargs) except OSError as e: self.assertEqual(e.errno, num) def assert_deprecated(self, fn, *args, **kwargs): with warnings.catch_warnings(record=True) as w: fn(*args, **kwargs) assert len(w) == 1 assert issubclass(w[-1].category, DeprecationWarning) @requires_posix class FunctionalTests(BaseTests): def setUp(self): self._environ = os.environ.copy() def tearDown(self): os.environ = self._environ def test_print_command(self): from sh import ls, which actual_location = which("ls") out = str(ls) self.assertEqual(out, actual_location) def test_unicode_arg(self): from sh import echo test = "漢字" if not IS_PY3: test = test.decode("utf8") p = echo(test, _encoding="utf8") output = p.strip() self.assertEqual(test, output) def test_unicode_exception(self): from sh import ErrorReturnCode py = create_tmp_test("exit(1)") arg = "漢字" if not IS_PY3: arg = arg.decode("utf8") try: python(py.name, arg, _encoding="utf8") except ErrorReturnCode as e: if IS_PY3: self.assertTrue(arg in str(e)) else: self.assertTrue(arg in unicode(e)) else: self.fail("exception wasn't raised") def test_pipe_fd(self): py = create_tmp_test("""print("hi world")""") read_fd, write_fd = os.pipe() python(py.name, _out=write_fd) out = os.read(read_fd, 10) self.assertEqual(out, b"hi world\n") def test_trunc_exc(self): py = create_tmp_test(""" import sys sys.stdout.write("a" * 1000) sys.stderr.write("b" * 1000) exit(1) """) self.assertRaises(sh.ErrorReturnCode, python, py.name) def test_number_arg(self): py = create_tmp_test(""" from optparse import OptionParser parser = OptionParser() options, args = parser.parse_args() print(args[0]) """) out = python(py.name, 3).strip() self.assertEqual(out, "3") def test_exit_code(self): from sh import ErrorReturnCode py = create_tmp_test(""" exit(3) """) self.assertRaises(ErrorReturnCode, python, py.name) def test_patched_glob(self): from glob import glob py = create_tmp_test(""" import sys print(sys.argv[1:]) """) files = glob("*.faowjefoajweofj") out = python(py.name, files).strip() self.assertEqual(out, "['*.faowjefoajweofj']") @requires_py35 def test_patched_glob_with_recursive_argument(self): from glob import glob py = create_tmp_test(""" import sys print(sys.argv[1:]) """) files = glob("*.faowjefoajweofj", recursive=True) out = python(py.name, files).strip() self.assertEqual(out, "['*.faowjefoajweofj']") def test_exit_code_with_hasattr(self): from sh import ErrorReturnCode py = create_tmp_test(""" exit(3) """) try: out = python(py.name, _iter=True) # hasattr can swallow exceptions hasattr(out, 'something_not_there') list(out) self.assertEqual(out.exit_code, 3) self.fail("Command exited with error, but no exception thrown") except ErrorReturnCode as e: pass def test_exit_code_from_exception(self): from sh import ErrorReturnCode py = create_tmp_test(""" exit(3) """) self.assertRaises(ErrorReturnCode, python, py.name) try: python(py.name) except Exception as e: self.assertEqual(e.exit_code, 3) def test_stdin_from_string(self): from sh import sed self.assertEqual(sed(_in="one test three", e="s/test/two/").strip(), "one two three") def test_ok_code(self): from sh import ls, ErrorReturnCode_1, ErrorReturnCode_2 exc_to_test = ErrorReturnCode_2 code_to_pass = 2 if IS_OSX: exc_to_test = ErrorReturnCode_1 code_to_pass = 1 self.assertRaises(exc_to_test, ls, "/aofwje/garogjao4a/eoan3on") ls("/aofwje/garogjao4a/eoan3on", _ok_code=code_to_pass) ls("/aofwje/garogjao4a/eoan3on", _ok_code=[code_to_pass]) ls("/aofwje/garogjao4a/eoan3on", _ok_code=range(code_to_pass + 1)) def test_ok_code_none(self): py = create_tmp_test("exit(0)") python(py.name, _ok_code=None) def test_quote_escaping(self): py = create_tmp_test(""" from optparse import OptionParser parser = OptionParser() options, args = parser.parse_args() print(args) """) out = python(py.name, "one two three").strip() self.assertEqual(out, "['one two three']") out = python(py.name, "one \"two three").strip() self.assertEqual(out, "['one \"two three']") out = python(py.name, "one", "two three").strip() self.assertEqual(out, "['one', 'two three']") out = python(py.name, "one", "two \"haha\" three").strip() self.assertEqual(out, "['one', 'two \"haha\" three']") out = python(py.name, "one two's three").strip() self.assertEqual(out, "[\"one two's three\"]") out = python(py.name, 'one two\'s three').strip() self.assertEqual(out, "[\"one two's three\"]") def test_multiple_pipes(self): from sh import tr, python import time py = create_tmp_test(""" import sys import os import time for l in "andrew": sys.stdout.write(l) time.sleep(.2) """) inc_py = create_tmp_test(""" import sys while True: letter = sys.stdin.read(1) if not letter: break sys.stdout.write(chr(ord(letter)+1)) """) def inc(proc, *args, **kwargs): return python(proc, "-u", inc_py.name, *args, **kwargs) class Derp(object): def __init__(self): self.times = [] self.stdout = [] self.last_received = None def agg(self, line): self.stdout.append(line.strip()) now = time.time() if self.last_received: self.times.append(now - self.last_received) self.last_received = now derp = Derp() p = inc( inc( inc( python("-u", py.name, _piped=True), _piped=True), _piped=True), _out=derp.agg) p.wait() self.assertEqual("".join(derp.stdout), "dqguhz") self.assertTrue(all([t > .15 for t in derp.times])) def test_manual_stdin_string(self): from sh import tr out = tr("[:lower:]", "[:upper:]", _in="andrew").strip() self.assertEqual(out, "ANDREW") def test_manual_stdin_iterable(self): from sh import tr test = ["testing\n", "herp\n", "derp\n"] out = tr("[:lower:]", "[:upper:]", _in=test) match = "".join([t.upper() for t in test]) self.assertEqual(out, match) def test_manual_stdin_file(self): from sh import tr import tempfile test_string = "testing\nherp\nderp\n" stdin = tempfile.NamedTemporaryFile() stdin.write(test_string.encode()) stdin.flush() stdin.seek(0) out = tr("[:lower:]", "[:upper:]", _in=stdin) self.assertEqual(out, test_string.upper()) def test_manual_stdin_queue(self): from sh import tr try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty test = ["testing\n", "herp\n", "derp\n"] q = Queue() for t in test: q.put(t) q.put(None) # EOF out = tr("[:lower:]", "[:upper:]", _in=q) match = "".join([t.upper() for t in test]) self.assertEqual(out, match) def test_environment(self): """ tests that environments variables that we pass into sh commands exist in the environment, and on the sh module """ import os # this is the environment we'll pass into our commands env = {"HERP": "DERP"} # python on osx will bizarrely add some extra environment variables that # i didn't ask for. for this test, we prune those out if they exist osx_cruft = [ "__CF_USER_TEXT_ENCODING", "__PYVENV_LAUNCHER__", "VERSIONER_PYTHON_PREFER_32_BIT", "VERSIONER_PYTHON_VERSION", ] # first we test that the environment exists in our child process as # we've set it py = create_tmp_test(""" import os osx_cruft = %s for key in osx_cruft: try: del os.environ[key] except: pass print(os.environ["HERP"] + " " + str(len(os.environ))) """ % osx_cruft) out = python(py.name, _env=env).strip() self.assertEqual(out, "DERP 1") py = create_tmp_test(""" import os, sys sys.path.insert(0, os.getcwd()) import sh osx_cruft = %s for key in osx_cruft: try: del os.environ[key] except: pass print(sh.HERP + " " + str(len(os.environ))) """ % osx_cruft) out = python(py.name, _env=env, _cwd=THIS_DIR).strip() self.assertEqual(out, "DERP 1") def test_which(self): from sh import which, ls self.assertEqual(which("fjoawjefojawe"), None) self.assertEqual(which("ls"), str(ls)) def test_which_paths(self): from sh import which py = create_tmp_test(""" print("hi") """) test_path = dirname(py.name) _, test_name = os.path.split(py.name) found_path = which(test_name) self.assertEqual(found_path, None) found_path = which(test_name, [test_path]) self.assertEqual(found_path, py.name) def test_no_arg(self): import pwd from sh import whoami u1 = whoami().strip() u2 = pwd.getpwuid(os.geteuid())[0] self.assertEqual(u1, u2) def test_incompatible_special_args(self): from sh import ls self.assertRaises(TypeError, ls, _iter=True, _piped=True) def test_exception(self): from sh import ErrorReturnCode_2 py = create_tmp_test(""" exit(2) """) self.assertRaises(ErrorReturnCode_2, python, py.name) def test_piped_exception1(self): from sh import ErrorReturnCode_2 py = create_tmp_test(""" import sys sys.stdout.write("line1\\n") sys.stdout.write("line2\\n") exit(2) """) py2 = create_tmp_test("") def fn(): list(python(python(py.name, _piped=True), "-u", py2.name, _iter=True)) self.assertRaises(ErrorReturnCode_2, fn) def test_piped_exception2(self): from sh import ErrorReturnCode_2 py = create_tmp_test(""" import sys sys.stdout.write("line1\\n") sys.stdout.write("line2\\n") exit(2) """) py2 = create_tmp_test("") def fn(): python(python(py.name, _piped=True), "-u", py2.name) self.assertRaises(ErrorReturnCode_2, fn) def test_command_not_found(self): from sh import CommandNotFound def do_import(): from sh import aowjgoawjoeijaowjellll self.assertRaises(ImportError, do_import) def do_import(): import sh sh.awoefaowejfw self.assertRaises(CommandNotFound, do_import) def do_import(): import sh sh.Command("ofajweofjawoe") self.assertRaises(CommandNotFound, do_import) def test_command_wrapper_equivalence(self): from sh import Command, ls, which self.assertEqual(Command(which("ls")), ls) def test_doesnt_execute_directories(self): save_path = os.environ['PATH'] bin_dir1 = tempfile.mkdtemp() bin_dir2 = tempfile.mkdtemp() gcc_dir1 = os.path.join(bin_dir1, 'gcc') gcc_file2 = os.path.join(bin_dir2, 'gcc') try: os.environ['PATH'] = os.pathsep.join((bin_dir1, bin_dir2)) # a folder named 'gcc', its executable, but should not be # discovered by internal which(1)-clone os.makedirs(gcc_dir1) # an executable named gcc -- only this should be executed bunk_header = '#!/bin/sh\necho $*' with open(gcc_file2, "w") as h: h.write(bunk_header) os.chmod(gcc_file2, int(0o755)) import sh from sh import gcc if IS_PY3: self.assertEqual(gcc._path, gcc_file2.encode(sh.DEFAULT_ENCODING)) else: self.assertEqual(gcc._path, gcc_file2) self.assertEqual(gcc('no-error').stdout.strip(), 'no-error'.encode("ascii")) finally: os.environ['PATH'] = save_path if exists(gcc_file2): os.unlink(gcc_file2) if exists(gcc_dir1): os.rmdir(gcc_dir1) if exists(bin_dir1): os.rmdir(bin_dir1) if exists(bin_dir1): os.rmdir(bin_dir2) def test_multiple_args_short_option(self): py = create_tmp_test(""" from optparse import OptionParser parser = OptionParser() parser.add_option("-l", dest="long_option") options, args = parser.parse_args() print(len(options.long_option.split())) """) num_args = int(python(py.name, l="one two three")) self.assertEqual(num_args, 3) num_args = int(python(py.name, "-l", "one's two's three's")) self.assertEqual(num_args, 3) def test_multiple_args_long_option(self): py = create_tmp_test(""" from optparse import OptionParser parser = OptionParser() parser.add_option("-l", "--long-option", dest="long_option") options, args = parser.parse_args() print(len(options.long_option.split())) """) num_args = int(python(py.name, long_option="one two three", nothing=False)) self.assertEqual(num_args, 3) num_args = int(python(py.name, "--long-option", "one's two's three's")) self.assertEqual(num_args, 3) def test_short_bool_option(self): py = create_tmp_test(""" from optparse import OptionParser parser = OptionParser() parser.add_option("-s", action="store_true", default=False, dest="short_option") options, args = parser.parse_args() print(options.short_option) """) self.assertTrue(python(py.name, s=True).strip() == "True") self.assertTrue(python(py.name, s=False).strip() == "False") self.assertTrue(python(py.name).strip() == "False") def test_long_bool_option(self): py = create_tmp_test(""" from optparse import OptionParser parser = OptionParser() parser.add_option("-l", "--long-option", action="store_true", default=False, dest="long_option") options, args = parser.parse_args() print(options.long_option) """) self.assertTrue(python(py.name, long_option=True).strip() == "True") self.assertTrue(python(py.name).strip() == "False") def test_composition(self): from sh import ls, wc c1 = int(wc(ls("-A1"), l=True)) c2 = len(os.listdir(".")) self.assertEqual(c1, c2) def test_incremental_composition(self): from sh import ls, wc c1 = int(wc(ls("-A1", _piped=True), l=True).strip()) c2 = len(os.listdir(".")) self.assertEqual(c1, c2) def test_short_option(self): from sh import sh s1 = sh(c="echo test").strip() s2 = "test" self.assertEqual(s1, s2) def test_long_option(self): py = create_tmp_test(""" from optparse import OptionParser parser = OptionParser() parser.add_option("-l", "--long-option", action="store", default="", dest="long_option") options, args = parser.parse_args() print(options.long_option.upper()) """) self.assertTrue(python(py.name, long_option="testing").strip() == "TESTING") self.assertTrue(python(py.name).strip() == "") def test_raw_args(self): py = create_tmp_test(""" from optparse import OptionParser parser = OptionParser() parser.add_option("--long_option", action="store", default=None, dest="long_option1") parser.add_option("--long-option", action="store", default=None, dest="long_option2") options, args = parser.parse_args() if options.long_option1: print(options.long_option1.upper()) else: print(options.long_option2.upper()) """) self.assertEqual(python(py.name, {"long_option": "underscore"}).strip(), "UNDERSCORE") self.assertEqual(python(py.name, long_option="hyphen").strip(), "HYPHEN") def test_custom_separator(self): py = create_tmp_test(""" import sys print(sys.argv[1]) """) opt = {"long-option": "underscore"} correct = "--long-option=custom=underscore" out = python(py.name, opt, _long_sep="=custom=").strip() self.assertEqual(out, correct) # test baking too correct = "--long-option=baked=underscore" python_baked = python.bake(py.name, opt, _long_sep="=baked=") out = python_baked().strip() self.assertEqual(out, correct) def test_custom_separator_space(self): py = create_tmp_test(""" import sys print(str(sys.argv[1:])) """) opt = {"long-option": "space"} correct = ["--long-option", "space"] out = python(py.name, opt, _long_sep=" ").strip() self.assertEqual(out, str(correct)) def test_custom_long_prefix(self): py = create_tmp_test(""" import sys print(sys.argv[1]) """) out = python(py.name, {"long-option": "underscore"}, _long_prefix="-custom-").strip() self.assertEqual(out, "-custom-long-option=underscore") # test baking too out = python.bake(py.name, {"long-option": "underscore"}, _long_prefix="-baked-")().strip() self.assertEqual(out, "-baked-long-option=underscore") def test_command_wrapper(self): from sh import Command, which ls = Command(which("ls")) wc = Command(which("wc")) c1 = int(wc(ls("-A1"), l=True)) c2 = len(os.listdir(".")) self.assertEqual(c1, c2) def test_background(self): from sh import sleep import time start = time.time() sleep_time = .5 p = sleep(sleep_time, _bg=True) now = time.time() self.assertTrue(now - start < sleep_time) p.wait() now = time.time() self.assertTrue(now - start > sleep_time) def test_background_exception(self): from sh import ls, ErrorReturnCode_1, ErrorReturnCode_2 p = ls("/ofawjeofj", _bg=True) # should not raise exc_to_test = ErrorReturnCode_2 if IS_OSX: exc_to_test = ErrorReturnCode_1 self.assertRaises(exc_to_test, p.wait) # should raise def test_with_context(self): from sh import whoami import getpass py = create_tmp_test(""" import sys import os import subprocess print("with_context") subprocess.Popen(sys.argv[1:], shell=False).wait() """) cmd1 = python.bake(py.name, _with=True) with cmd1: out = whoami() self.assertTrue("with_context" in out) self.assertTrue(getpass.getuser() in out) def test_with_context_args(self): from sh import whoami import getpass py = create_tmp_test(""" import sys import os import subprocess from optparse import OptionParser parser = OptionParser() parser.add_option("-o", "--opt", action="store_true", default=False, dest="opt") options, args = parser.parse_args() if options.opt: subprocess.Popen(args[0], shell=False).wait() """) with python(py.name, opt=True, _with=True): out = whoami() self.assertTrue(getpass.getuser() == out.strip()) with python(py.name, _with=True): out = whoami() self.assertTrue(out == "") def test_binary_input(self): py = create_tmp_test(""" import sys data = sys.stdin.read() sys.stdout.write(data) """) data = b'1234' out = python(py.name, _in=data) self.assertEqual(out, "1234") def test_err_to_out(self): py = create_tmp_test(""" import sys import os sys.stdout.write("stdout") sys.stdout.flush() sys.stderr.write("stderr") sys.stderr.flush() """) stdout = python(py.name, _err_to_out=True) self.assertEqual(stdout, "stdoutstderr") def test_err_to_out_and_sys_stdout(self): py = create_tmp_test(""" import sys import os sys.stdout.write("stdout") sys.stdout.flush() sys.stderr.write("stderr") sys.stderr.flush() """) master, slave = os.pipe() stdout = python(py.name, _err_to_out=True, _out=slave) self.assertEqual(stdout, "") self.assertEqual(os.read(master, 12), b"stdoutstderr") def test_err_piped(self): py = create_tmp_test(""" import sys sys.stderr.write("stderr") """) py2 = create_tmp_test(""" import sys while True: line = sys.stdin.read() if not line: break sys.stdout.write(line) """) out = python(python("-u", py.name, _piped="err"), "-u", py2.name) self.assertEqual(out, "stderr") def test_out_redirection(self): import tempfile py = create_tmp_test(""" import sys import os sys.stdout.write("stdout") sys.stderr.write("stderr") """) file_obj = tempfile.NamedTemporaryFile() out = python(py.name, _out=file_obj) self.assertTrue(len(out) == 0) file_obj.seek(0) actual_out = file_obj.read() file_obj.close() self.assertTrue(len(actual_out) != 0) # test with tee file_obj = tempfile.NamedTemporaryFile() out = python(py.name, _out=file_obj, _tee=True) self.assertTrue(len(out) != 0) file_obj.seek(0) actual_out = file_obj.read() file_obj.close() self.assertTrue(len(actual_out) != 0) def test_err_redirection(self): import tempfile py = create_tmp_test(""" import sys import os sys.stdout.write("stdout") sys.stderr.write("stderr") """) file_obj = tempfile.NamedTemporaryFile() p = python("-u", py.name, _err=file_obj) file_obj.seek(0) stderr = file_obj.read().decode() file_obj.close() self.assertTrue(p.stdout == b"stdout") self.assertTrue(stderr == "stderr") self.assertTrue(len(p.stderr) == 0) # now with tee file_obj = tempfile.NamedTemporaryFile() p = python(py.name, _err=file_obj, _tee="err") file_obj.seek(0) stderr = file_obj.read().decode() file_obj.close() self.assertTrue(p.stdout == b"stdout") self.assertTrue(stderr == "stderr") self.assertTrue(len(p.stderr) != 0) def test_tty_tee(self): py = create_tmp_test(""" import sys sys.stdout.write("stdout") """) read, write = pty.openpty() out = python("-u", py.name, _out=write).stdout tee = os.read(read, 6) self.assertEqual(out, b"") self.assertEqual(tee, b"stdout") os.close(write) os.close(read) read, write = pty.openpty() out = python("-u", py.name, _out=write, _tee=True).stdout tee = os.read(read, 6) self.assertEqual(out, b"stdout") self.assertEqual(tee, b"stdout") os.close(write) os.close(read) def test_err_redirection_actual_file(self): import tempfile file_obj = tempfile.NamedTemporaryFile() py = create_tmp_test(""" import sys import os sys.stdout.write("stdout") sys.stderr.write("stderr") """) stdout = python("-u", py.name, _err=file_obj.name).wait() file_obj.seek(0) stderr = file_obj.read().decode() file_obj.close() self.assertTrue(stdout == "stdout") self.assertTrue(stderr == "stderr") def test_subcommand_and_bake(self): from sh import ls import getpass py = create_tmp_test(""" import sys import os import subprocess print("subcommand") subprocess.Popen(sys.argv[1:], shell=False).wait() """) cmd1 = python.bake(py.name) out = cmd1.whoami() self.assertTrue("subcommand" in out) self.assertTrue(getpass.getuser() in out) def test_multiple_bakes(self): py = create_tmp_test(""" import sys sys.stdout.write(str(sys.argv[1:])) """) out = python.bake(py.name).bake("bake1").bake("bake2")() self.assertEqual("['bake1', 'bake2']", out) def test_arg_preprocessor(self): py = create_tmp_test(""" import sys sys.stdout.write(str(sys.argv[1:])) """) def arg_preprocess(args, kwargs): args.insert(0, "preprocessed") kwargs["a-kwarg"] = 123 return args, kwargs cmd = python.bake(py.name, _arg_preprocess=arg_preprocess) out = cmd("arg") self.assertEqual("['preprocessed', 'arg', '--a-kwarg=123']", out) def test_bake_args_come_first(self): from sh import ls ls = ls.bake(h=True) ran = ls("-la").ran ft = ran.index("-h") self.assertTrue("-la" in ran[ft:]) def test_output_equivalence(self): from sh import whoami iam1 = whoami() iam2 = whoami() self.assertEqual(iam1, iam2) # https://github.com/amoffat/sh/pull/252 def test_stdout_pipe(self): py = create_tmp_test(r""" import sys sys.stdout.write("foobar\n") """) read_fd, write_fd = os.pipe() p = python(py.name, _out=write_fd, u=True) def alarm(sig, action): self.fail("Timeout while reading from pipe") import signal signal.signal(signal.SIGALRM, alarm) signal.alarm(3) data = os.read(read_fd, 100) self.assertEqual(b"foobar\n", data) signal.alarm(0) signal.signal(signal.SIGALRM, signal.SIG_DFL) def test_stdout_callback(self): py = create_tmp_test(""" import sys import os for i in range(5): print(i) """) stdout = [] def agg(line): stdout.append(line) p = python("-u", py.name, _out=agg) p.wait() self.assertTrue(len(stdout) == 5) def test_stdout_callback_no_wait(self): import time py = create_tmp_test(""" import sys import os import time for i in range(5): print(i) time.sleep(.5) """) stdout = [] def agg(line): stdout.append(line) p = python("-u", py.name, _out=agg, _bg=True) # we give a little pause to make sure that the NamedTemporaryFile # exists when the python process actually starts time.sleep(.5) self.assertTrue(len(stdout) != 5) def test_stdout_callback_line_buffered(self): py = create_tmp_test(""" import sys import os for i in range(5): print("herpderp") """) stdout = [] def agg(line): stdout.append(line) p = python("-u", py.name, _out=agg, _out_bufsize=1) p.wait() self.assertTrue(len(stdout) == 5) def test_stdout_callback_line_unbuffered(self): py = create_tmp_test(""" import sys import os for i in range(5): print("herpderp") """) stdout = [] def agg(char): stdout.append(char) p = python("-u", py.name, _out=agg, _out_bufsize=0) p.wait() # + 5 newlines self.assertTrue(len(stdout) == (len("herpderp") * 5 + 5)) def test_stdout_callback_buffered(self): py = create_tmp_test(""" import sys import os for i in range(5): sys.stdout.write("herpderp") """) stdout = [] def agg(chunk): stdout.append(chunk) p = python("-u", py.name, _out=agg, _out_bufsize=4) p.wait() self.assertTrue(len(stdout) == (len("herp") / 2 * 5)) def test_stdout_callback_with_input(self): py = create_tmp_test(""" import sys import os IS_PY3 = sys.version_info[0] == 3 if IS_PY3: raw_input = input for i in range(5): print(str(i)) derp = raw_input("herp? ") print(derp) """) def agg(line, stdin): if line.strip() == "4": stdin.put("derp\n") p = python("-u", py.name, _out=agg, _tee=True) p.wait() self.assertTrue("derp" in p) def test_stdout_callback_exit(self): py = create_tmp_test(""" import sys import os for i in range(5): print(i) """) stdout = [] def agg(line): line = line.strip() stdout.append(line) if line == "2": return True p = python("-u", py.name, _out=agg, _tee=True) p.wait() self.assertTrue("4" in p) self.assertTrue("4" not in stdout) def test_stdout_callback_terminate(self): import signal py = create_tmp_test(""" import sys import os import time for i in range(5): print(i) time.sleep(.5) """) stdout = [] def agg(line, stdin, process): line = line.strip() stdout.append(line) if line == "3": process.terminate() return True import sh caught_signal = False try: p = python("-u", py.name, _out=agg, _bg=True) p.wait() except sh.SignalException_SIGTERM: caught_signal = True self.assertTrue(caught_signal) self.assertEqual(p.process.exit_code, -signal.SIGTERM) self.assertTrue("4" not in p) self.assertTrue("4" not in stdout) def test_stdout_callback_kill(self): import signal py = create_tmp_test(""" import sys import os import time for i in range(5): print(i) time.sleep(.5) """) stdout = [] def agg(line, stdin, process): line = line.strip() stdout.append(line) if line == "3": process.kill() return True import sh caught_signal = False try: p = python("-u", py.name, _out=agg, _bg=True) p.wait() except sh.SignalException_SIGKILL: caught_signal = True self.assertTrue(caught_signal) self.assertEqual(p.process.exit_code, -signal.SIGKILL) self.assertTrue("4" not in p) self.assertTrue("4" not in stdout) def test_general_signal(self): import signal from signal import SIGINT py = create_tmp_test(""" import sys import os import time import signal def sig_handler(sig, frame): print(10) exit(0) signal.signal(signal.SIGINT, sig_handler) for i in range(5): print(i) sys.stdout.flush() time.sleep(0.5) """) stdout = [] def agg(line, stdin, process): line = line.strip() stdout.append(line) if line == "3": process.signal(SIGINT) return True p = python(py.name, _out=agg, _tee=True) p.wait() self.assertEqual(p.process.exit_code, 0) self.assertEqual(p, "0\n1\n2\n3\n10\n") def test_iter_generator(self): py = create_tmp_test(""" import sys import os import time for i in range(42): print(i) sys.stdout.flush() """) out = [] for line in python(py.name, _iter=True): out.append(int(line.strip())) self.assertTrue(len(out) == 42 and sum(out) == 861) def test_iter_unicode(self): # issue https://github.com/amoffat/sh/issues/224 test_string = "\xe4\xbd\x95\xe4\xbd\x95\n" * 150 # len > buffer_s txt = create_tmp_test(test_string) for line in sh.cat(txt.name, _iter=True): break self.assertTrue(len(line) < 1024) def test_nonblocking_iter(self): from errno import EWOULDBLOCK py = create_tmp_test(""" import time import sys time.sleep(1) sys.stdout.write("stdout") """) count = 0 value = None for line in python(py.name, _iter_noblock=True): if line == EWOULDBLOCK: count += 1 else: value = line self.assertTrue(count > 0) self.assertEqual(value, "stdout") py = create_tmp_test(""" import time import sys time.sleep(1) sys.stderr.write("stderr") """) count = 0 value = None for line in python(py.name, _iter_noblock="err"): if line == EWOULDBLOCK: count += 1 else: value = line self.assertTrue(count > 0) self.assertEqual(value, "stderr") def test_for_generator_to_err(self): py = create_tmp_test(""" import sys import os for i in range(42): sys.stderr.write(str(i)+"\\n") """) out = [] for line in python("-u", py.name, _iter="err"): out.append(line) self.assertTrue(len(out) == 42) # verify that nothing is going to stdout out = [] for line in python("-u", py.name, _iter="out"): out.append(line) self.assertTrue(len(out) == 0) def test_sigpipe(self): import sh py1 = create_tmp_test(""" import sys import os import time import signal # by default, python disables SIGPIPE, in favor of using IOError exceptions, so # let's put that back to the system default where we terminate with a signal # exit code signal.signal(signal.SIGPIPE, signal.SIG_DFL) for letter in "andrew": time.sleep(0.6) print(letter) """) py2 = create_tmp_test(""" import sys import os import time while True: line = sys.stdin.readline() if not line: break print(line.strip().upper()) exit(0) """) p1 = python("-u", py1.name, _piped="out") p2 = python(p1, "-u", py2.name) # SIGPIPE should happen, but it shouldn't be an error, since _piped is # truthful self.assertEqual(-p1.exit_code, signal.SIGPIPE) self.assertEqual(p2.exit_code, 0) def test_piped_generator(self): from sh import tr from string import ascii_uppercase import time py1 = create_tmp_test(""" import sys import os import time for letter in "andrew": time.sleep(0.6) print(letter) """) py2 = create_tmp_test(""" import sys import os import time while True: line = sys.stdin.readline() if not line: break print(line.strip().upper()) """) times = [] last_received = None letters = "" for line in python(python("-u", py1.name, _piped="out"), "-u", py2.name, _iter=True): if not letters: start = time.time() letters += line.strip() now = time.time() if last_received: times.append(now - last_received) last_received = now self.assertEqual("ANDREW", letters) self.assertTrue(all([t > .3 for t in times])) def test_generator_and_callback(self): py = create_tmp_test(""" import sys import os for i in range(42): sys.stderr.write(str(i * 2)+"\\n") print(i) """) stderr = [] def agg(line): stderr.append(int(line.strip())) out = [] for line in python("-u", py.name, _iter=True, _err=agg): out.append(line) self.assertTrue(len(out) == 42) self.assertTrue(sum(stderr) == 1722) def test_cast_bg(self): py = create_tmp_test(""" import sys import time time.sleep(0.5) sys.stdout.write(sys.argv[1]) """) self.assertEqual(int(python(py.name, "123", _bg=True)), 123) self.assertEqual(long(python(py.name, "456", _bg=True)), 456) self.assertEqual(float(python(py.name, "789", _bg=True)), 789.0) def test_cmd_eq(self): py = create_tmp_test("") cmd1 = python.bake(py.name, "-u") cmd2 = python.bake(py.name, "-u") cmd3 = python.bake(py.name) self.assertEqual(cmd1, cmd2) self.assertNotEqual(cmd1, cmd3) def test_fg(self): py = create_tmp_test("exit(0)") # notice we're using `sh.python`, and not `python`. this is because # `python` has an env baked into it, and we want `_env` to be None for # coverage sh.python(py.name, _fg=True) def test_fg_env(self): py = create_tmp_test(""" import os code = int(os.environ.get("EXIT", "0")) exit(code) """) env = os.environ.copy() env["EXIT"] = "3" self.assertRaises(sh.ErrorReturnCode_3, python, py.name, _fg=True, _env=env) def test_fg_alternative(self): py = create_tmp_test("exit(0)") python(py.name, _in=sys.stdin, _out=sys.stdout, _err=sys.stderr) def test_fg_exc(self): py = create_tmp_test("exit(1)") self.assertRaises(sh.ErrorReturnCode_1, python, py.name, _fg=True) def test_out_filename(self): outfile = tempfile.NamedTemporaryFile() py = create_tmp_test("print('output')") python(py.name, _out=outfile.name) outfile.seek(0) self.assertEqual(b"output\n", outfile.read()) def test_bg_exit_code(self): py = create_tmp_test(""" import time time.sleep(1) exit(49) """) p = python(py.name, _ok_code=49, _bg=True) self.assertEqual(49, p.exit_code) def test_cwd(self): from sh import pwd from os.path import realpath self.assertEqual(str(pwd(_cwd="/tmp")), realpath("/tmp") + "\n") self.assertEqual(str(pwd(_cwd="/etc")), realpath("/etc") + "\n") def test_huge_piped_data(self): from sh import tr stdin = tempfile.NamedTemporaryFile() data = "herpderp" * 4000 + "\n" stdin.write(data.encode()) stdin.flush() stdin.seek(0) out = tr(tr("[:lower:]", "[:upper:]", _in=data), "[:upper:]", "[:lower:]") self.assertTrue(out == data) def test_tty_input(self): py = create_tmp_test(""" import sys import os if os.isatty(sys.stdin.fileno()): sys.stdout.write("password?\\n") sys.stdout.flush() pw = sys.stdin.readline().strip() sys.stdout.write("%s\\n" % ("*" * len(pw))) sys.stdout.flush() else: sys.stdout.write("no tty attached!\\n") sys.stdout.flush() """) test_pw = "test123" expected_stars = "*" * len(test_pw) d = {} def password_enterer(line, stdin): line = line.strip() if not line: return if line == "password?": stdin.put(test_pw + "\n") elif line.startswith("*"): d["stars"] = line return True pw_stars = python(py.name, _tty_in=True, _out=password_enterer) pw_stars.wait() self.assertEqual(d["stars"], expected_stars) response = python(py.name) self.assertEqual(response, "no tty attached!\n") def test_tty_output(self): py = create_tmp_test(""" import sys import os if os.isatty(sys.stdout.fileno()): sys.stdout.write("tty attached") sys.stdout.flush() else: sys.stdout.write("no tty attached") sys.stdout.flush() """) out = python(py.name, _tty_out=True) self.assertEqual(out, "tty attached") out = python(py.name, _tty_out=False) self.assertEqual(out, "no tty attached") def test_stringio_output(self): from sh import echo out = StringIO() echo("-n", "testing 123", _out=out) self.assertEqual(out.getvalue(), "testing 123") out = cStringIO() echo("-n", "testing 123", _out=out) self.assertEqual(out.getvalue().decode(), "testing 123") out = ioStringIO() echo("-n", "testing 123", _out=out) self.assertEqual(out.getvalue(), "testing 123") out = iocStringIO() echo("-n", "testing 123", _out=out) self.assertEqual(out.getvalue().decode(), "testing 123") def test_stringio_input(self): from sh import cat input = StringIO() input.write("herpderp") input.seek(0) out = cat(_in=input) self.assertEqual(out, "herpderp") def test_internal_bufsize(self): from sh import cat output = cat(_in="a"*1000, _internal_bufsize=100, _out_bufsize=0) self.assertEqual(len(output), 100) output = cat(_in="a"*1000, _internal_bufsize=50, _out_bufsize=2) self.assertEqual(len(output), 100) def test_change_stdout_buffering(self): py = create_tmp_test(""" import sys import os # this proves that we won't get the output into our callback until we send # a newline sys.stdout.write("switch ") sys.stdout.flush() sys.stdout.write("buffering\\n") sys.stdout.flush() sys.stdin.read(1) sys.stdout.write("unbuffered") sys.stdout.flush() # this is to keep the output from being flushed by the process ending, which # would ruin our test. we want to make sure we get the string "unbuffered" # before the process ends, without writing a newline sys.stdin.read(1) """) d = { "newline_buffer_success": False, "unbuffered_success": False, } def interact(line, stdin, process): line = line.strip() if not line: return if line == "switch buffering": d["newline_buffer_success"] = True process.change_out_bufsize(0) stdin.put("a") elif line == "unbuffered": stdin.put("b") d["unbuffered_success"] = True return True # start with line buffered stdout pw_stars = python("-u", py.name, _out=interact, _out_bufsize=1) pw_stars.wait() self.assertTrue(d["newline_buffer_success"]) self.assertTrue(d["unbuffered_success"]) def test_callable_interact(self): py = create_tmp_test(""" import sys sys.stdout.write("line1") """) class Callable(object): def __init__(self): self.line = None def __call__(self, line): self.line = line cb = Callable() python(py.name, _out=cb) self.assertEqual(cb.line, "line1") def test_encoding(self): return raise NotImplementedError("what's the best way to test a different \ '_encoding' special keyword argument?") def test_timeout(self): import sh from time import time sleep_for = 3 timeout = 1 started = time() try: sh.sleep(sleep_for, _timeout=timeout).wait() except sh.TimeoutException: pass else: self.fail("no timeout exception") elapsed = time() - started self.assertTrue(abs(elapsed - timeout) < 0.5) def test_timeout_overstep(self): started = time.time() sh.sleep(1, _timeout=5) elapsed = time.time() - started self.assertTrue(abs(elapsed - 1) < 0.5) def test_binary_pipe(self): binary = b'\xec;\xedr\xdbF' py1 = create_tmp_test(""" import sys import os sys.stdout = os.fdopen(sys.stdout.fileno(), "wb", 0) sys.stdout.write(b'\\xec;\\xedr\\xdbF') """) py2 = create_tmp_test(""" import sys import os sys.stdin = os.fdopen(sys.stdin.fileno(), "rb", 0) sys.stdout = os.fdopen(sys.stdout.fileno(), "wb", 0) sys.stdout.write(sys.stdin.read()) """) out = python(python(py1.name), py2.name) self.assertEqual(out.stdout, binary) # designed to trigger the "... (%d more, please see e.stdout)" output # of the ErrorReturnCode class def test_failure_with_large_output(self): from sh import ErrorReturnCode_1 py = create_tmp_test(""" print("andrewmoffat" * 1000) exit(1) """) self.assertRaises(ErrorReturnCode_1, python, py.name) # designed to check if the ErrorReturnCode constructor does not raise # an UnicodeDecodeError def test_non_ascii_error(self): from sh import ls, ErrorReturnCode test = "/á" # coerce to unicode if IS_PY3: pass else: test = test.decode("utf8") self.assertRaises(ErrorReturnCode, ls, test) def test_no_out(self): py = create_tmp_test(""" import sys sys.stdout.write("stdout") sys.stderr.write("stderr") """) p = python(py.name, _no_out=True) self.assertEqual(p.stdout, b"") self.assertEqual(p.stderr, b"stderr") self.assertTrue(p.process._pipe_queue.empty()) def callback(line): pass p = python(py.name, _out=callback) self.assertEqual(p.stdout, b"") self.assertEqual(p.stderr, b"stderr") self.assertTrue(p.process._pipe_queue.empty()) p = python(py.name) self.assertEqual(p.stdout, b"stdout") self.assertEqual(p.stderr, b"stderr") self.assertFalse(p.process._pipe_queue.empty()) def test_tty_stdin(self): py = create_tmp_test(""" import sys sys.stdout.write(sys.stdin.read()) sys.stdout.flush() """) out = python(py.name, _in="test\n", _tty_in=True) self.assertEqual("test\n", out) def test_no_err(self): py = create_tmp_test(""" import sys sys.stdout.write("stdout") sys.stderr.write("stderr") """) p = python(py.name, _no_err=True) self.assertEqual(p.stderr, b"") self.assertEqual(p.stdout, b"stdout") self.assertFalse(p.process._pipe_queue.empty()) def callback(line): pass p = python(py.name, _err=callback) self.assertEqual(p.stderr, b"") self.assertEqual(p.stdout, b"stdout") self.assertFalse(p.process._pipe_queue.empty()) p = python(py.name) self.assertEqual(p.stderr, b"stderr") self.assertEqual(p.stdout, b"stdout") self.assertFalse(p.process._pipe_queue.empty()) def test_no_pipe(self): from sh import ls # calling a command regular should fill up the pipe_queue p = ls() self.assertFalse(p.process._pipe_queue.empty()) # calling a command with a callback should not def callback(line): pass p = ls(_out=callback) self.assertTrue(p.process._pipe_queue.empty()) # calling a command regular with no_pipe also should not p = ls(_no_pipe=True) self.assertTrue(p.process._pipe_queue.empty()) def test_decode_error_handling(self): from functools import partial py = create_tmp_test(""" # -*- coding: utf8 -*- import sys import os sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb') IS_PY3 = sys.version_info[0] == 3 if IS_PY3: sys.stdout.write(bytes("te漢字st", "utf8")) else: sys.stdout.write("te漢字st") """) fn = partial(python, py.name, _encoding="ascii") def s(fn): str(fn()) self.assertRaises(UnicodeDecodeError, s, fn) p = python(py.name, _encoding="ascii", _decode_errors="ignore") self.assertEqual(p, "test") def test_signal_exception(self): from sh import SignalException_15 def throw_terminate_signal(): py = create_tmp_test(""" import time while True: time.sleep(1) """) to_kill = python(py.name, _bg=True) to_kill.terminate() to_kill.wait() self.assertRaises(SignalException_15, throw_terminate_signal) def test_signal_group(self): child = create_tmp_test(""" import time time.sleep(3) """) parent = create_tmp_test(""" import sh p = sh.python("{child_file}", _bg=True, _new_session=False) print(p.pid) print(p.process.pgid) p.wait() """, child_file=child.name) def launch(): p = python(parent.name, _bg=True, _iter=True) child_pid = int(next(p).strip()) child_pgid = int(next(p).strip()) parent_pid = p.pid parent_pgid = p.process.pgid return p, child_pid, child_pgid, parent_pid, parent_pgid def assert_alive(pid): os.kill(pid, 0) def assert_dead(pid): self.assert_oserror(errno.ESRCH, os.kill, pid, 0) # first let's prove that calling regular SIGKILL on the parent does # nothing to the child, since the child was launched in the same process # group (_new_session=False) and the parent is not a controlling process p, child_pid, child_pgid, parent_pid, parent_pgid = launch() assert_alive(parent_pid) assert_alive(child_pid) p.kill() time.sleep(0.1) assert_dead(parent_pid) assert_alive(child_pid) self.assertRaises(sh.SignalException_SIGKILL, p.wait) assert_dead(child_pid) # now let's prove that killing the process group kills both the parent # and the child p, child_pid, child_pgid, parent_pid, parent_pgid = launch() assert_alive(parent_pid) assert_alive(child_pid) p.kill_group() time.sleep(0.1) assert_dead(parent_pid) assert_dead(child_pid) def test_pushd(self): """ test basic pushd functionality """ old_wd1 = sh.pwd().strip() old_wd2 = os.getcwd() self.assertEqual(old_wd1, old_wd2) self.assertNotEqual(old_wd1, tempdir) with sh.pushd(tempdir): new_wd1 = sh.pwd().strip() new_wd2 = os.getcwd() old_wd3 = sh.pwd().strip() old_wd4 = os.getcwd() self.assertEqual(old_wd3, old_wd4) self.assertEqual(old_wd1, old_wd3) self.assertEqual(new_wd1, tempdir) self.assertEqual(new_wd2, tempdir) def test_pushd_cd(self): """ test that pushd works like pushd/popd with built-in cd correctly """ import sh from sh import mkdir child = realpath(tempfile.mkdtemp()) try: old_wd = os.getcwd() with sh.pushd(tempdir): self.assertEqual(tempdir, os.getcwd()) sh.cd(child) self.assertEqual(child, os.getcwd()) self.assertEqual(old_wd, os.getcwd()) finally: os.rmdir(child) def test_cd_homedir(self): orig = os.getcwd() my_dir = os.path.expanduser("~") sh.cd() self.assertNotEqual(orig, os.getcwd()) self.assertEqual(my_dir, os.getcwd()) def test_non_existant_cwd(self): from sh import ls # sanity check non_exist_dir = join(tempdir, "aowjgoahewro") self.assertFalse(exists(non_exist_dir)) self.assertRaises(OSError, ls, _cwd=non_exist_dir) # https://github.com/amoffat/sh/issues/176 def test_baked_command_can_be_printed(self): from sh import ls ll = ls.bake("-l") self.assertTrue(str(ll).endswith("/ls -l")) # https://github.com/amoffat/sh/issues/185 def test_done_callback(self): import time class Callback(object): def __init__(self): self.called = False self.exit_code = None self.success = None def __call__(self, p, success, exit_code): self.called = True self.exit_code = exit_code self.success = success py = create_tmp_test(""" from time import time, sleep sleep(1) print(time()) """) callback = Callback() p = python(py.name, _done=callback, _bg=True) # do a little setup to prove that a command with a _done callback is run # in the background wait_start = time.time() p.wait() wait_elapsed = time.time() - wait_start self.assertTrue(callback.called) self.assertTrue(abs(wait_elapsed - 1.0) < 1.0) self.assertEqual(callback.exit_code, 0) self.assertTrue(callback.success) def test_fork_exc(self): from sh import ForkException py = create_tmp_test("") def fail(): raise RuntimeError("nooo") self.assertRaises(ForkException, python, py.name, _preexec_fn=fail) def test_new_session(self): from threading import Event py = create_tmp_test(""" import os import time pid = os.getpid() pgid = os.getpgid(pid) sid = os.getsid(pid) stuff = [pid, pgid, sid] print(",".join([str(el) for el in stuff])) time.sleep(0.5) """) event = Event() def handle(line, stdin, p): pid, pgid, sid = line.strip().split(",") pid = int(pid) pgid = int(pgid) sid = int(sid) self.assertEqual(p.pid, pid) self.assertEqual(pid, pgid) self.assertEqual(p.pgid, pgid) self.assertEqual(pgid, p.get_pgid()) self.assertEqual(pid, sid) self.assertEqual(sid, pgid) self.assertEqual(p.sid, sid) self.assertEqual(sid, p.get_sid()) event.set() # new session p = python(py.name, _out=handle) p.wait() self.assertTrue(event.is_set()) event.clear() def handle(line, stdin, p): pid, pgid, sid = line.strip().split(",") pid = int(pid) pgid = int(pgid) sid = int(sid) test_pid = os.getpgid(os.getpid()) self.assertEqual(p.pid, pid) self.assertNotEqual(test_pid, pgid) self.assertEqual(p.pgid, pgid) self.assertEqual(pgid, p.get_pgid()) self.assertNotEqual(pid, sid) self.assertNotEqual(sid, pgid) self.assertEqual(p.sid, sid) self.assertEqual(sid, p.get_sid()) event.set() # no new session p = python(py.name, _out=handle, _new_session=False) p.wait() self.assertTrue(event.is_set()) def test_done_cb_exc(self): from sh import ErrorReturnCode class Callback(object): def __init__(self): self.called = False self.success = None def __call__(self, p, success, exit_code): self.success = success self.called = True py = create_tmp_test("exit(1)") callback = Callback() try: p = python(py.name, _done=callback, _bg=True) p.wait() except ErrorReturnCode: self.assertTrue(callback.called) self.assertFalse(callback.success) else: self.fail("command should've thrown an exception") def test_callable_stdin(self): py = create_tmp_test(""" import sys sys.stdout.write(sys.stdin.read()) """) def create_stdin(): state = {"count": 0} def stdin(): count = state["count"] if count == 4: return None state["count"] += 1 return str(count) return stdin out = python(py.name, _in=create_stdin()) self.assertEqual("0123", out) def test_stdin_unbuffered_bufsize(self): import sh from time import sleep # this tries to receive some known data and measures the time it takes # to receive it. since we're flushing by newline, we should only be # able to receive the data when a newline is fed in py = create_tmp_test(""" import sys from time import time started = time() data = sys.stdin.read(len("testing")) waited = time() - started sys.stdout.write(data + "\\n") sys.stdout.write(str(waited) + "\\n") started = time() data = sys.stdin.read(len("done")) waited = time() - started sys.stdout.write(data + "\\n") sys.stdout.write(str(waited) + "\\n") sys.stdout.flush() """) def create_stdin(): yield "test" sleep(1) yield "ing" sleep(1) yield "done" out = python(py.name, _in=create_stdin(), _in_bufsize=0) word1, time1, word2, time2, _ = out.split("\n") time1 = float(time1) time2 = float(time2) self.assertEqual(word1, "testing") self.assertTrue(abs(1-time1) < 0.5) self.assertEqual(word2, "done") self.assertTrue(abs(1-time2) < 0.5) def test_stdin_newline_bufsize(self): import sh from time import sleep # this tries to receive some known data and measures the time it takes # to receive it. since we're flushing by newline, we should only be # able to receive the data when a newline is fed in py = create_tmp_test(""" import sys from time import time started = time() data = sys.stdin.read(len("testing\\n")) waited = time() - started sys.stdout.write(data) sys.stdout.write(str(waited) + "\\n") started = time() data = sys.stdin.read(len("done\\n")) waited = time() - started sys.stdout.write(data) sys.stdout.write(str(waited) + "\\n") sys.stdout.flush() """) # we'll feed in text incrementally, sleeping strategically before # sending a newline. we then measure the amount that we slept # indirectly in the child process def create_stdin(): yield "test" sleep(1) yield "ing\n" sleep(1) yield "done\n" out = python(py.name, _in=create_stdin(), _in_bufsize=1) word1, time1, word2, time2, _ = out.split("\n") time1 = float(time1) time2 = float(time2) self.assertEqual(word1, "testing") self.assertTrue(abs(1-time1) < 0.5) self.assertEqual(word2, "done") self.assertTrue(abs(1-time2) < 0.5) def test_custom_timeout_signal(self): from sh import TimeoutException import signal py = create_tmp_test(""" import time time.sleep(3) """) try: python(py.name, _timeout=1, _timeout_signal=signal.SIGQUIT) except TimeoutException as e: self.assertEqual(e.exit_code, signal.SIGQUIT) else: self.fail("we should have handled a TimeoutException") def test_append_stdout(self): py = create_tmp_test(""" import sys num = sys.stdin.read() sys.stdout.write(num) """) append_file = tempfile.NamedTemporaryFile(mode="a+b") python(py.name, _in="1", _out=append_file) python(py.name, _in="2", _out=append_file) append_file.seek(0) output = append_file.read() self.assertEqual(b"12", output) def test_shadowed_subcommand(self): py = create_tmp_test(""" import sys sys.stdout.write(sys.argv[1]) """) out = python.bake(py.name).bake_() self.assertEqual("bake", out) def test_no_proc_no_attr(self): py = create_tmp_test("") with python(py.name) as p: self.assertRaises(AttributeError, getattr, p, "exit_code") def test_partially_applied_callback(self): from functools import partial py = create_tmp_test(""" for i in range(10): print(i) """) output = [] def fn(foo, line): output.append((foo, int(line.strip()))) log_line = partial(fn, "hello") out = python(py.name, _out=log_line) self.assertEqual(output, [("hello", i) for i in range(10)]) output = [] def fn(foo, line, stdin, proc): output.append((foo, int(line.strip()))) log_line = partial(fn, "hello") out = python(py.name, _out=log_line) self.assertEqual(output, [("hello", i) for i in range(10)]) # https://github.com/amoffat/sh/issues/266 def test_grandchild_no_sighup(self): import time # child process that will write to a file if it receives a SIGHUP child = create_tmp_test(""" import signal import sys import time output_file = sys.argv[1] with open(output_file, "w") as f: def handle_sighup(signum, frame): f.write("got signal %d" % signum) sys.exit(signum) signal.signal(signal.SIGHUP, handle_sighup) time.sleep(2) f.write("made it!\\n") """) # the parent that will terminate before the child writes to the output # file, potentially causing a SIGHUP parent = create_tmp_test(""" import os import time import sys child_file = sys.argv[1] output_file = sys.argv[2] os.spawnlp(os.P_NOWAIT, "python", "python", child_file, output_file) time.sleep(1) # give child a chance to set up """) output_file = tempfile.NamedTemporaryFile(delete=True) python(parent.name, child.name, output_file.name) time.sleep(3) out = output_file.readlines()[0] self.assertEqual(out, b"made it!\n") def test_unchecked_producer_failure(self): from sh import ErrorReturnCode_2 producer = create_tmp_test(""" import sys for i in range(10): print(i) sys.exit(2) """) consumer = create_tmp_test(""" import sys for line in sys.stdin: pass """) direct_pipe = python(producer.name, _piped=True) self.assertRaises(ErrorReturnCode_2, python, direct_pipe, consumer.name) def test_unchecked_pipeline_failure(self): # similar to test_unchecked_producer_failure, but this # tests a multi-stage pipeline from sh import ErrorReturnCode_2 producer = create_tmp_test(""" import sys for i in range(10): print(i) sys.exit(2) """) middleman = create_tmp_test(""" import sys for line in sys.stdin: print("> " + line) """) consumer = create_tmp_test(""" import sys for line in sys.stdin: pass """) producer_normal_pipe = python(producer.name, _piped=True) middleman_normal_pipe = python(producer_normal_pipe, middleman.name, _piped=True) self.assertRaises(ErrorReturnCode_2, python, middleman_normal_pipe, consumer.name) @skip_unless(HAS_MOCK, "requires unittest.mock") class MockTests(BaseTests): def test_patch_command_cls(self): def fn(): cmd = sh.Command("afowejfow") return cmd() @unittest.mock.patch("sh.Command") def test(Command): Command().return_value = "some output" return fn() self.assertEqual(test(), "some output") self.assertRaises(sh.CommandNotFound, fn) def test_patch_command(self): def fn(): return sh.afowejfow() @unittest.mock.patch("sh.afowejfow", create=True) def test(cmd): cmd.return_value = "some output" return fn() self.assertEqual(test(), "some output") self.assertRaises(sh.CommandNotFound, fn) class MiscTests(BaseTests): @requires_poller("poll") def test_fd_over_1024(self): py = create_tmp_test("""print("hi world")""") with ulimit(resource.RLIMIT_NOFILE, 2048): cutoff_fd = 1024 pipes = [] for i in xrange(cutoff_fd): master, slave = os.pipe() pipes.append((master, slave)) if slave >= cutoff_fd: break python(py.name) for master, slave in pipes: os.close(master) os.close(slave) def test_args_deprecated(self): self.assertRaises(DeprecationWarning, sh.args, _env={}) def test_cant_import_all(self): def go(): # we have to use exec, because in py3, this syntax raises a # SyntaxError upon compilation exec("from sh import *") self.assertRaises(RuntimeError, go) def test_percent_doesnt_fail_logging(self): """ test that a command name doesn't interfere with string formatting in the internal loggers """ py = create_tmp_test(""" print("cool") """) out = python(py.name, "%") out = python(py.name, "%%") out = python(py.name, "%%%") # TODO # for some reason, i can't get a good stable baseline measured in this test # on osx. so skip it for now if osx @not_osx @requires_progs("lsof") def test_no_fd_leak(self): import sh import os from itertools import product # options whose combinations can possibly cause fd leaks kwargs = { "_tty_out": (True, False), "_tty_in": (True, False), "_err_to_out": (True, False), } def get_opts(possible_values): all_opts = [] for opt, values in possible_values.items(): opt_collection = [] all_opts.append(opt_collection) for val in values: pair = (opt, val) opt_collection.append(pair) for combo in product(*all_opts): opt_dict = {} for key, val in combo: opt_dict[key] = val yield opt_dict test_pid = os.getpid() def get_num_fds(): lines = sh.lsof(p=test_pid).strip().split("\n") def test(line): line = line.upper() return "CHR" in line or "PIPE" in line lines = [line for line in lines if test(line)] return len(lines) - 1 py = create_tmp_test("") def test_command(**opts): python(py.name, **opts) # make sure our baseline is stable.. we can remove this test_command() baseline = get_num_fds() for i in xrange(10): test_command() num_fds = get_num_fds() self.assertEqual(baseline, num_fds) for opts in get_opts(kwargs): for i in xrange(2): test_command(**opts) num_fds = get_num_fds() self.assertEqual(baseline, num_fds, (baseline, num_fds, opts)) def test_pushd_thread_safety(self): import threading import time temp1 = realpath(tempfile.mkdtemp()) temp2 = realpath(tempfile.mkdtemp()) try: results = [None, None] def fn1(): with sh.pushd(temp1): time.sleep(0.2) results[0] = realpath(os.getcwd()) def fn2(): time.sleep(0.1) with sh.pushd(temp2): results[1] = realpath(os.getcwd()) time.sleep(0.3) t1 = threading.Thread(name="t1", target=fn1) t2 = threading.Thread(name="t2", target=fn2) t1.start() t2.start() t1.join() t2.join() self.assertEqual(results, [temp1, temp2]) finally: os.rmdir(temp1) os.rmdir(temp2) def test_stdin_nohang(self): py = create_tmp_test(""" print("hi") """) read, write = os.pipe() stdin = os.fdopen(read, "r") python(py.name, _in=stdin) @requires_utf8 def test_unicode_path(self): from sh import Command py = create_tmp_test("""#!/usr/bin/env python # -*- coding: utf8 -*- print("字") """, "字", delete=False) try: py.close() os.chmod(py.name, int(0o755)) cmd = Command(py.name) # all of these should behave just fine str(cmd) repr(cmd) unicode(cmd) running = cmd() str(running) repr(running) unicode(running) str(running.process) repr(running.process) unicode(running.process) finally: os.unlink(py.name) # https://github.com/amoffat/sh/issues/121 def test_wraps(self): from sh import ls wraps(ls)(lambda f: True) def test_signal_exception_aliases(self): """ proves that signal exceptions with numbers and names are equivalent """ import signal import sh sig_name = "SignalException_%d" % signal.SIGQUIT sig = getattr(sh, sig_name) from sh import SignalException_SIGQUIT self.assertEqual(sig, SignalException_SIGQUIT) def test_change_log_message(self): py = create_tmp_test(""" print("cool") """) def log_msg(cmd, call_args, pid=None): return "Hi! I ran something" buf = StringIO() handler = logging.StreamHandler(buf) logger = logging.getLogger("sh") logger.setLevel(logging.INFO) try: logger.addHandler(handler) python(py.name, "meow", "bark", _log_msg=log_msg) finally: logger.removeHandler(handler) loglines = buf.getvalue().split("\n") self.assertTrue(loglines, "Log handler captured no messages?") self.assertTrue(loglines[0].startswith("Hi! I ran something")) # https://github.com/amoffat/sh/issues/273 def test_stop_iteration_doesnt_block(self): """ proves that calling calling next() on a stopped iterator doesn't hang. """ import sh py = create_tmp_test(""" print("cool") """) p = python(py.name, _iter=True) for i in range(100): try: next(p) except StopIteration: pass # https://github.com/amoffat/sh/issues/195 def test_threaded_with_contexts(self): import sh import threading import time py = create_tmp_test(""" import sys a = sys.argv res = (a[1], a[3]) sys.stdout.write(repr(res)) """) p1 = python.bake("-u", py.name, 1) p2 = python.bake("-u", py.name, 2) results = [None, None] def f1(): with p1: time.sleep(1) results[0] = str(sh.python("one")) def f2(): with p2: results[1] = str(sh.python("two")) t1 = threading.Thread(target=f1) t1.start() t2 = threading.Thread(target=f2) t2.start() t1.join() t2.join() correct = [ "('1', 'one')", "('2', 'two')", ] self.assertEqual(results, correct) # https://github.com/amoffat/sh/pull/292 def test_eintr(self): import signal def handler(num, frame): pass signal.signal(signal.SIGALRM, handler) py = create_tmp_test(""" import time time.sleep(2) """) p = python(py.name, _bg=True) signal.alarm(1) p.wait() class StreamBuffererTests(unittest.TestCase): def test_unbuffered(self): from sh import _disable_whitelist, StreamBufferer b = StreamBufferer(0) self.assertEqual(b.process(b"test"), [b"test"]) self.assertEqual(b.process(b"one"), [b"one"]) self.assertEqual(b.process(b""), [b""]) self.assertEqual(b.flush(), b"") def test_newline_buffered(self): from sh import _disable_whitelist, StreamBufferer b = StreamBufferer(1) self.assertEqual(b.process(b"testing\none\ntwo"), [b"testing\n", b"one\n"]) self.assertEqual(b.process(b"\nthree\nfour"), [b"two\n", b"three\n"]) self.assertEqual(b.flush(), b"four") def test_chunk_buffered(self): from sh import _disable_whitelist, StreamBufferer b = StreamBufferer(10) self.assertEqual(b.process(b"testing\none\ntwo"), [b"testing\non"]) self.assertEqual(b.process(b"\nthree\n"), [b"e\ntwo\nthre"]) self.assertEqual(b.flush(), b"e\n") @requires_posix class ExecutionContextTests(unittest.TestCase): def test_basic(self): import sh out = StringIO() _sh = sh(_out=out) _sh.echo("-n", "TEST") self.assertEqual("TEST", out.getvalue()) def test_no_interfere1(self): import sh out = StringIO() _sh = sh(_out=out) from _sh import echo echo("-n", "TEST") self.assertEqual("TEST", out.getvalue()) # Emptying the StringIO out.seek(0) out.truncate(0) sh.echo("-n", "KO") self.assertEqual("", out.getvalue()) def test_no_interfere2(self): import sh out = StringIO() from sh import echo _sh = sh(_out=out) echo("-n", "TEST") self.assertEqual("", out.getvalue()) def test_no_bad_name(self): out = StringIO() def fn(): import sh sh = sh(_out=out) self.assertRaises(RuntimeError, fn) def test_set_in_parent_function(self): import sh out = StringIO() _sh = sh(_out=out) def nested1(): _sh.echo("-n", "TEST1") def nested2(): import sh sh.echo("-n", "TEST2") nested1() nested2() self.assertEqual("TEST1", out.getvalue()) def test_reimport_no_interfere(self): import sh out = StringIO() _sh = sh(_out=out) import _sh # this reimport '_sh' from the eponymous local variable _sh.echo("-n", "TEST") self.assertEqual("TEST", out.getvalue()) def test_importer_detects_module_name(self): import sh _sh = sh() omg = _sh from omg import python def test_importer_only_works_with_sh(self): def unallowed_import(): _os = os from _os import path self.assertRaises(ImportError, unallowed_import) if __name__ == "__main__": root = logging.getLogger() root.setLevel(logging.DEBUG) root.addHandler(NullHandler()) test_kwargs = {} if IS_PY2 and MINOR_VER != 6: test_kwargs["failfast"] = True test_kwargs["verbosity"] = 2 try: # if we're running a specific test, we can let unittest framework figure out # that test and run it itself. it will also handle setting the return code # of the process if any tests error or fail if len(sys.argv) > 1: unittest.main(**test_kwargs) # otherwise, it looks like we want to run all the tests else: suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__]) test_kwargs["verbosity"] = 2 result = unittest.TextTestRunner(**test_kwargs).run(suite) if not result.wasSuccessful(): exit(1) finally: if cov: cov.stop() cov.save()