Skip to content
This repository was archived by the owner on Apr 24, 2018. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
*.pyc
.tox/
*.egg-info/
*.py[co]
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ language: python
python:
- 2.6
- 2.7
- 3.2
- 3.3
- pypy

script: python test_envoy.py
20 changes: 16 additions & 4 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion envoy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@

# -*- coding: utf-8 -*-

from .core import Command, ConnectedCommand, Response
from .core import expand_args, run, connect
Expand Down
56 changes: 33 additions & 23 deletions envoy/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -47,6 +48,7 @@ def _is_alive(thread):


class Command(object):

def __init__(self, cmd):
self.cmd = cmd
self.process = None
Expand All @@ -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,
Expand All @@ -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):
Expand All @@ -102,30 +103,41 @@ 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

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):
Expand All @@ -147,24 +159,20 @@ 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
self.std_out = None
self.status_code = None
self.history = []


def __repr__(self):
if len(self.command):
return '<Response [{0}]>'.format(self.command[0])
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand Down
9 changes: 3 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__,
Expand All @@ -26,8 +23,7 @@
author='Kenneth Reitz',
author_email='[email protected]',
url='https://github.com/kennethreitz/envoy',
packages= ['envoy'],
install_requires=required,
packages=['envoy'],
license='MIT',
classifiers=(
'Development Status :: 5 - Production/Stable',
Expand All @@ -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',
),
)
8 changes: 4 additions & 4 deletions test_envoy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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__":
Expand Down