Skip to content
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
9 changes: 9 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,15 @@ To get a stripped, unicode string version of bash.stdout call value()::
>>> b = bash('ls tests.py').value()
u'tests.py'

To get the results (separated by newlines) as a list::

>>> b = bash('ls . ').results()
['bash.pyc', 'tests.pyc']

or use the iterator directly::

>>> b = [res for res in bash('ls . ')]
['bash.pyc', 'tests.pyc']

Motivation
----------
Expand Down
13 changes: 13 additions & 0 deletions bash/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import re
import sys
from subprocess import PIPE, Popen
SUBPROCESS_HAS_TIMEOUT = True
Expand All @@ -9,6 +10,8 @@
# will mean you don't have access to things like timeout
SUBPROCESS_HAS_TIMEOUT = False

SPLIT_NEWLINE_REGEX = re.compile(' *\n *')


class bash(object):
"This is lower class because it is intended to be used as a method."
Expand Down Expand Up @@ -54,7 +57,17 @@ def __nonzero__(self):
def __bool__(self):
return bool(self.value())

def __iter__(self):
return self.results().__iter__()

def value(self):
if self.stdout:
return self.stdout.strip().decode(encoding='UTF-8')
return ''

def results(self):
output = self.stdout.decode(encoding='UTF-8').strip() or ''
if output:
return SPLIT_NEWLINE_REGEX.split(output)
else:
return []
9 changes: 9 additions & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,12 @@ def test_sync_false_does_not_wait(self):
self.assertTrue((t2-t1).total_seconds() < 0.5)
b.sync()
self.assertEqual(b.stdout, b'1\n')

def test_iterate_over_results(self):
expecting = ['setup.py', 'tests.py']
b = bash('ls . | grep "\.py"')
results = b.results()
self.assertEqual(results, expecting)

iteratedResults = [result for result in b]
self.assertEqual(iteratedResults, expecting)