-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvorlauf.py
97 lines (71 loc) · 2.32 KB
/
vorlauf.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import subprocess
from pipes import quote
class Pipeline(object):
def __init__(self, initial=None):
self.pipeline = []
if initial is None:
return
for process in initial:
self.add(process)
def add(self, process):
self.pipeline.append(process)
def create_processes(self, stdin, stdout):
processes = []
total = len(self)
for i in range(len(self)):
process = self.pipeline[i]
is_final = (i == total-1)
is_first = (i == 0)
proc_stdin = stdin if is_first else processes[i-1].stdout
proc_stdout = stdout if is_final else subprocess.PIPE
processes.append(process.run(
stdin=proc_stdin,
stdout=proc_stdout,
))
return processes
def run(self, stdin=None, stdout=None):
processes = self.create_processes(stdin, stdout)
last_process = processes[-1]
first_process = processes[0]
last_process.communicate()
first_process.wait()
return processes
def __or__(self, process):
if not isinstance(process, Process):
raise TypeError('Unsupported operand type')
self.add(process)
return self
def __len__(self):
return len(self.pipeline)
def __unicode__(self):
return u' | '.join((unicode(p) for p in self.pipeline))
__str__ = __unicode__
def __repr__(self):
return u'<{} {}>'.format(
self.__class__.__name__,
self.__unicode__(),
)
class Process(object):
def __init__(self, *args, **kwargs):
self.args = args
self.popen_kwargs = kwargs
def __or__(self, process):
if not isinstance(process, Process):
raise TypeError('Unsupported operand type')
return Pipeline([self, process])
def run(self, stdin=None, stdout=None, stderr=None):
return subprocess.Popen(
self.args,
stdin=stdin,
stdout=stdout,
stderr=stderr,
**self.popen_kwargs
)
def __unicode__(self):
return quote(u' '.join(self.args))
__str__ = __unicode__
def __repr__(self):
return u'<{} {}>'.format(
self.__class__.__name__,
self.__unicode__()
)