diff --git a/.gitignore b/.gitignore index 0d20b64..c7bd84a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ -*.pyc +.tox/ +*.egg-info/ +*.py[co] diff --git a/.travis.yml b/.travis.yml index 5a81f25..d4167b2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,6 +3,8 @@ language: python python: - 2.6 - 2.7 + - 3.2 + - 3.3 - pypy script: python test_envoy.py diff --git a/LICENSE b/LICENSE index 520107e..be0013a 100644 --- a/LICENSE +++ b/LICENSE @@ -1,7 +1,19 @@ -Copyright (c) 2013 Kenneth Reitz +Copyright (c) 2014 Kenneth Reitz -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: +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 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. +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. diff --git a/envoy/__init__.py b/envoy/__init__.py index a9b4c2b..9e08c54 100644 --- a/envoy/__init__.py +++ b/envoy/__init__.py @@ -1,4 +1,4 @@ - +# -*- coding: utf-8 -*- from .core import Command, ConnectedCommand, Response from .core import expand_args, run, connect diff --git a/envoy/core.py b/envoy/core.py index 5220391..047bab5 100644 --- a/envoy/core.py +++ b/envoy/core.py @@ -25,7 +25,8 @@ def _terminate_process(process): if sys.platform == 'win32': import ctypes PROCESS_TERMINATE = 1 - handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid) + handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, + process.pid) ctypes.windll.kernel32.TerminateProcess(handle, -1) ctypes.windll.kernel32.CloseHandle(handle) else: @@ -47,6 +48,7 @@ def _is_alive(thread): class Command(object): + def __init__(self, cmd): self.cmd = cmd self.process = None @@ -62,9 +64,9 @@ def run(self, data, timeout, kill_timeout, env, cwd): environ.update(env or {}) def target(): - try: - self.process = subprocess.Popen(self.cmd, + self.process = subprocess.Popen( + self.cmd, universal_newlines=True, shell=False, env=environ, @@ -77,21 +79,20 @@ def target(): if sys.version_info[0] >= 3: self.out, self.err = self.process.communicate( - input = bytes(self.data, "UTF-8") if self.data else None + input=bytes(self.data, "UTF-8") if self.data else None ) else: self.out, self.err = self.process.communicate(self.data) except Exception as exc: self.exc = exc - thread = threading.Thread(target=target) thread.start() thread.join(timeout) if self.exc: raise self.exc - if _is_alive(thread) : + if _is_alive(thread): _terminate_process(self.process) thread.join(kill_timeout) if _is_alive(thread): @@ -102,17 +103,12 @@ def target(): class ConnectedCommand(object): - def __init__(self, - process=None, - std_in=None, - std_out=None, - std_err=None): + def __init__(self, process=None, std_in=None, std_out=None, std_err=None): self._process = process - self.std_in = std_in - self.std_out = std_out - self.std_err = std_out - self._status_code = None + self.std_in = std_in or process.stdin + self._std_out = std_out or '' + self._std_err = std_err or '' def __enter__(self): return self @@ -120,12 +116,28 @@ def __enter__(self): def __exit__(self, type, value, traceback): self.kill() + @property + def std_out(self): + if not self._process.stdout.closed: + out, err = self._process.communicate() + self._std_out += out + self._std_err += err + return self._std_out + + @property + def std_err(self): + if not self._process.stderr.closed: + out, err = self._process.communicate() + self._std_out += out + self._std_err += err + return self._std_err + @property def status_code(self): """The status code of the process. If the code is None, assume that it's still running. """ - return self._status_code + return self._process.poll() @property def pid(self): @@ -147,16 +159,13 @@ def send(self, str, end='\n'): def block(self): """Blocks until command finishes. Returns Response instance.""" - self._status_code = self._process.wait() - + self._process.wait() class Response(object): """A command's response""" def __init__(self, process=None): - super(Response, self).__init__() - self._process = process self.command = None self.std_err = None @@ -164,7 +173,6 @@ def __init__(self, process=None): self.status_code = None self.history = [] - def __repr__(self): if len(self.command): return ''.format(self.command[0]) @@ -194,7 +202,8 @@ def expand_args(command): return command -def run(command, data=None, timeout=None, kill_timeout=None, env=None, cwd=None): +def run(command, data=None, timeout=None, + kill_timeout=None, env=None, cwd=None): """Executes a given commmand and returns Response. Blocks until process is complete, or timeout is reached. @@ -240,7 +249,8 @@ def connect(command, data=None, env=None, cwd=None): environ = dict(os.environ) environ.update(env or {}) - process = subprocess.Popen(command_str, + process = subprocess.Popen( + command_str, universal_newlines=True, shell=False, env=environ, diff --git a/setup.py b/setup.py index c5c3007..feb2449 100755 --- a/setup.py +++ b/setup.py @@ -11,13 +11,10 @@ from distutils.core import setup - if sys.argv[-1] == "publish": os.system("python setup.py sdist bdist_wheel upload") sys.exit() -required = [] - setup( name='envoy', version=envoy.__version__, @@ -26,8 +23,7 @@ author='Kenneth Reitz', author_email='me@kennethreitz.com', url='https://github.com/kennethreitz/envoy', - packages= ['envoy'], - install_requires=required, + packages=['envoy'], license='MIT', classifiers=( 'Development Status :: 5 - Production/Stable', @@ -38,7 +34,8 @@ 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', + 'Programming Language :: Python :: 3.2', + 'Programming Language :: Python :: 3.3', ), ) diff --git a/test_envoy.py b/test_envoy.py index 18e148d..c8a6ded 100644 --- a/test_envoy.py +++ b/test_envoy.py @@ -23,7 +23,7 @@ def test_timeout(self): # THIS TEST FAILS BECAUSE expand_args DOESN'T HANDLE QUOTES PROPERLY def test_quoted_args(self): sentinel = 'quoted_args' * 3 - r = envoy.run("python -c 'print \"%s\"'" % sentinel) + r = envoy.run("""python -c 'print("%s")'""" % sentinel) self.assertEqual(r.std_out.rstrip(), sentinel) self.assertEqual(r.status_code, 0) @@ -44,14 +44,14 @@ def test_status_code_success(self): self.assertEqual(c.status_code, 0) def test_status_code_failure(self): - c = envoy.connect("sleeep 1") - self.assertEqual(c.status_code, 127) + c = envoy.connect("sleep -1") + self.assertNotEqual(c.status_code, 0) def test_input(self): test_string = 'asdfQWER' r = envoy.connect("cat | tr [:lower:] [:upper:]") r.send(test_string) - self.assertEqual(r.std_out, test_string.upper()) + self.assertEqual(r.std_out.strip(), test_string.upper()) self.assertEqual(r.status_code, 0) if __name__ == "__main__":