Working pipey chain, woo.

This commit is contained in:
Harry
2014-11-04 11:31:55 +00:00
parent 85b39fe4b6
commit acfae7ac2a
2 changed files with 19 additions and 30 deletions
+17 -28
View File
@@ -60,13 +60,14 @@ class Process(object):
self._subprocess = subprocess.Popen(
args=self.command,
shell=True,
stdin=self._stdin if self.stdin else subprocess.PIPE,
stdout=self._sdout if self.stdout else subprocess.PIPE,
stdin=self._stdin if self._stdin else subprocess.PIPE,
stdout=self._stdout if self._stdout else subprocess.PIPE,
)
def wait(self):
self._returncode = self._subprocess.wait()
self._stdout_text = self._subprocess.stdout.read().decode()
if self._subprocess.stdout is not None:
self._stdout_text = self._subprocess.stdout.read().decode()
def run(self):
@@ -74,45 +75,28 @@ class Process(object):
self.wait()
def __or__(self, other):
return Chain([self, other])
class Chain(object):
def __init__(self, processes=None):
self.processes = processes if processes is not None else []
def __init__(self, processes):
self.processes = processes
def process(self, command):
p = Process(command)
self.processes.append(p)
return p
def link(self, x, y):
print('Linking {} to {}'.format(x, y))
def start(self, wait=False):
for process in self.processes:
process.start()
self.wait()
def wait(self):
# wait, somehow
pass
def run(self):
for proc, next_proc in zip(self.processes, self.processes[1:]):
read, write = os.pipe()
proc.set_stdout(write)
next_proc.set_stdin(read)
for proc in reversed(self.processes):
print('starting', proc)
for proc in self.processes:
proc.start()
self.processes[-1].wait()
for proc in self.processes:
proc.wait()
if proc._stdout is not None:
os.close(proc._stdout)
@property
@@ -120,6 +104,11 @@ class Chain(object):
return self.processes[-1].returncode
@property
def stdout(self):
return self.processes[-1].stdout
def chain():
return Chain()
+2 -2
View File
@@ -9,10 +9,10 @@ TEST_DIR = os.path.abspath(os.path.join(
def test_chained_procs():
ls = Process('ls')
ls = Process('ls {test_dir}'.format(test_dir=TEST_DIR))
grep = Process('grep 2')
chain = ls | grep
chain.run()
assert chain.returncode == 0
assert chain.stdout == 'file2'
assert chain.stdout.strip() == 'file2'