diff --git a/README.rst b/README.rst index 339dc65..73afaf8 100644 --- a/README.rst +++ b/README.rst @@ -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 ---------- diff --git a/bash/__init__.py b/bash/__init__.py index d8da050..2630fba 100644 --- a/bash/__init__.py +++ b/bash/__init__.py @@ -1,3 +1,4 @@ +import re import sys from subprocess import PIPE, Popen SUBPROCESS_HAS_TIMEOUT = True @@ -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." @@ -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 [] diff --git a/tests.py b/tests.py index 41263b4..babc0de 100644 --- a/tests.py +++ b/tests.py @@ -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)