596
|
1 #!/usr/bin/env python
|
|
2
|
|
3 """
|
|
4 multiprocessing/subprocess experiments
|
|
5 """
|
|
6
|
|
7 import argparse
|
|
8 import os
|
|
9 import subprocess
|
|
10 import sys
|
|
11 import time
|
|
12 import tempfile
|
|
13
|
606
|
14 string = (str, unicode)
|
|
15
|
601
|
16 class Process(subprocess.Popen):
|
|
17 """why would you name a subprocess object Popen?"""
|
|
18
|
606
|
19 # http://docs.python.org/2/library/subprocess.html#popen-constructor
|
610
|
20 defaults = {'bufsize': 1, # line buffered
|
611
|
21 'store_output': True, # store stdout
|
603
|
22 }
|
|
23
|
606
|
24 def __init__(self, command, **kwargs):
|
|
25
|
|
26 # setup arguments
|
|
27 self.command = command
|
|
28 _kwargs = self.defaults.copy()
|
|
29 _kwargs.update(kwargs)
|
|
30
|
607
|
31 # on unix, ``shell={True|False}`` should always come from the
|
|
32 # type of command (string or list)
|
609
|
33 if not subprocess.mswindows:
|
607
|
34 _kwargs['shell'] = isinstance(command, string)
|
|
35
|
606
|
36 # output buffer
|
611
|
37 self.location = 0
|
606
|
38 self.output_buffer = tempfile.SpooledTemporaryFile()
|
611
|
39 self.output = '' if _kwargs.pop('store_output') else None
|
606
|
40 _kwargs['stdout'] = self.output_buffer
|
|
41
|
611
|
42 # runtime
|
|
43 self.start = time.time()
|
|
44 self.end = None
|
|
45
|
606
|
46 # launch subprocess
|
607
|
47 subprocess.Popen.__init__(self, command, **_kwargs)
|
606
|
48
|
611
|
49 def _finalize(self, process_output):
|
|
50 """internal function to finalize"""
|
|
51
|
|
52 # read final output
|
|
53 self.read(process_output)
|
|
54
|
614
|
55 # reset output buffer location
|
611
|
56 self.output_buffer.seek(0)
|
|
57
|
|
58 # set end time
|
|
59 self.end = time.time()
|
|
60
|
614
|
61 def poll(self, process_output=None):
|
|
62
|
|
63 if process_output is not None:
|
|
64 self.read(process_output) # read from output buffer
|
|
65 poll = subprocess.Popen.poll(self)
|
|
66 if poll is not None:
|
|
67 self._finalize(process_output)
|
|
68 return poll
|
613
|
69
|
611
|
70 def wait(self, maxtime=None, sleep=1., process_output=None):
|
606
|
71 """
|
|
72 maxtime -- timeout in seconds
|
|
73 sleep -- number of seconds to sleep between polling
|
|
74 """
|
614
|
75 while self.poll(process_output) is None:
|
606
|
76
|
|
77 # check for timeout
|
|
78 curr_time = time.time()
|
613
|
79 run_time = self.runtime()
|
612
|
80 if maxtime is not None and run_time > maxtime:
|
611
|
81 self.kill()
|
|
82 self._finalize(process_output)
|
|
83 return
|
606
|
84
|
|
85 # naptime
|
|
86 if sleep:
|
|
87 time.sleep(sleep)
|
|
88
|
611
|
89 # finalize
|
613
|
90 self._finalize(process_output)
|
608
|
91
|
|
92 return self.returncode # set by ``.poll()``
|
606
|
93
|
611
|
94 def read(self, process_output=None):
|
610
|
95 """read from the output buffer"""
|
611
|
96
|
610
|
97 self.output_buffer.seek(self.location)
|
|
98 read = self.output_buffer.read()
|
611
|
99 if self.output is not None:
|
|
100 self.output += read
|
|
101 if process_output:
|
|
102 process_output(read)
|
610
|
103 self.location += len(read)
|
|
104 return read
|
|
105
|
606
|
106 def commandline(self):
|
|
107 """returns string of command line"""
|
|
108
|
|
109 if isinstance(self.command, string):
|
|
110 return self.command
|
|
111 return subprocess.list2cmdline(self.command)
|
|
112
|
|
113 __str__ = commandline
|
|
114
|
611
|
115 def runtime(self):
|
|
116 """returns time spent running or total runtime if completed"""
|
|
117
|
|
118 if self.end is None:
|
613
|
119 return time.time() - self.start
|
|
120 return self.end - self.start
|
611
|
121
|
596
|
122
|
|
123 def main(args=sys.argv[1:]):
|
599
|
124 """CLI"""
|
596
|
125
|
600
|
126 # available programs
|
|
127 progs = {'yes': ["yes"],
|
|
128 'ping': ['ping', 'google.com']}
|
|
129
|
599
|
130 # parse command line
|
611
|
131 parser = argparse.ArgumentParser(description=__doc__)
|
596
|
132 parser.add_argument("-t", "--time", dest="time",
|
599
|
133 type=float, default=4.,
|
614
|
134 help="seconds to run for (or <= 0 for forever)")
|
599
|
135 parser.add_argument("-s", "--sleep", dest="sleep",
|
596
|
136 type=float, default=1.,
|
600
|
137 help="sleep this number of seconds between polling")
|
|
138 parser.add_argument("-p", "--prog", dest='program',
|
606
|
139 choices=progs.keys(), default='ping',
|
600
|
140 help="subprocess to run")
|
606
|
141 parser.add_argument("--list-programs", dest='list_programs',
|
|
142 action='store_true', default=False,
|
|
143 help="list available programs")
|
596
|
144 options = parser.parse_args(args)
|
|
145
|
608
|
146 # list programs
|
|
147 if options.list_programs:
|
|
148 for key in sorted(progs.keys()):
|
|
149 print ('{}: {}'.format(key, subprocess.list2cmdline(progs[key])))
|
610
|
150 sys.exit(0)
|
599
|
151
|
|
152 # select program
|
600
|
153 prog = progs[options.program]
|
599
|
154
|
611
|
155 # start process
|
608
|
156 proc = Process(prog)
|
596
|
157
|
611
|
158 # callback for output processing
|
|
159 def process_output(output):
|
614
|
160 print ('[{}] {}{}'.format(proc.runtime(),
|
|
161 output.upper(),
|
|
162 '-==-'*10))
|
613
|
163
|
614
|
164 # start the main subprocess loop
|
|
165 while proc.poll(process_output) is None:
|
613
|
166
|
614
|
167 if options.time > 0 and proc.runtime() > options.time:
|
|
168 proc.kill()
|
608
|
169
|
614
|
170 if options.sleep:
|
|
171 time.sleep(options.sleep)
|
596
|
172
|
611
|
173 # wait for being done
|
614
|
174 #proc.wait(maxtime=options.time, sleep=options.sleep, process_output=process_output)
|
611
|
175
|
614
|
176 # correctness tests
|
|
177 assert proc.end is not None
|
|
178
|
|
179 # print summary
|
611
|
180 output = proc.output
|
|
181 n_lines = len(output.splitlines())
|
596
|
182 print ("{}: {} lines".format(subprocess.list2cmdline(prog), n_lines))
|
|
183
|
|
184 if __name__ == '__main__':
|
|
185 main()
|