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
|
|
55 # reset output buffer
|
|
56 self.output_buffer.seek(0)
|
|
57
|
|
58 # set end time
|
|
59 self.end = time.time()
|
|
60
|
613
|
61 def poll(self):
|
|
62 return subprocess.Popen.poll(self)
|
|
63
|
611
|
64 def wait(self, maxtime=None, sleep=1., process_output=None):
|
606
|
65 """
|
|
66 maxtime -- timeout in seconds
|
|
67 sleep -- number of seconds to sleep between polling
|
|
68 """
|
|
69 while self.poll() is None:
|
|
70
|
|
71 # check for timeout
|
|
72 curr_time = time.time()
|
613
|
73 run_time = self.runtime()
|
612
|
74 if maxtime is not None and run_time > maxtime:
|
611
|
75 self.kill()
|
|
76 self._finalize(process_output)
|
|
77 return
|
606
|
78
|
607
|
79 # read from output buffer
|
611
|
80 self.read(process_output)
|
607
|
81
|
606
|
82 # naptime
|
|
83 if sleep:
|
|
84 time.sleep(sleep)
|
|
85
|
611
|
86 # finalize
|
613
|
87 self._finalize(process_output)
|
608
|
88
|
|
89 return self.returncode # set by ``.poll()``
|
606
|
90
|
611
|
91 def read(self, process_output=None):
|
610
|
92 """read from the output buffer"""
|
611
|
93
|
610
|
94 self.output_buffer.seek(self.location)
|
|
95 read = self.output_buffer.read()
|
611
|
96 if self.output is not None:
|
|
97 self.output += read
|
|
98 if process_output:
|
|
99 process_output(read)
|
610
|
100 self.location += len(read)
|
|
101 return read
|
|
102
|
606
|
103 def commandline(self):
|
|
104 """returns string of command line"""
|
|
105
|
|
106 if isinstance(self.command, string):
|
|
107 return self.command
|
|
108 return subprocess.list2cmdline(self.command)
|
|
109
|
|
110 __str__ = commandline
|
|
111
|
611
|
112 def runtime(self):
|
|
113 """returns time spent running or total runtime if completed"""
|
|
114
|
|
115 if self.end is None:
|
613
|
116 return time.time() - self.start
|
|
117 return self.end - self.start
|
611
|
118
|
596
|
119
|
|
120 def main(args=sys.argv[1:]):
|
599
|
121 """CLI"""
|
596
|
122
|
600
|
123 # available programs
|
|
124 progs = {'yes': ["yes"],
|
|
125 'ping': ['ping', 'google.com']}
|
|
126
|
599
|
127 # parse command line
|
611
|
128 parser = argparse.ArgumentParser(description=__doc__)
|
596
|
129 parser.add_argument("-t", "--time", dest="time",
|
599
|
130 type=float, default=4.,
|
|
131 help="seconds to run for")
|
|
132 parser.add_argument("-s", "--sleep", dest="sleep",
|
596
|
133 type=float, default=1.,
|
600
|
134 help="sleep this number of seconds between polling")
|
|
135 parser.add_argument("-p", "--prog", dest='program',
|
606
|
136 choices=progs.keys(), default='ping',
|
600
|
137 help="subprocess to run")
|
606
|
138 parser.add_argument("--list-programs", dest='list_programs',
|
|
139 action='store_true', default=False,
|
|
140 help="list available programs")
|
596
|
141 options = parser.parse_args(args)
|
|
142
|
608
|
143 # list programs
|
|
144 if options.list_programs:
|
|
145 for key in sorted(progs.keys()):
|
|
146 print ('{}: {}'.format(key, subprocess.list2cmdline(progs[key])))
|
610
|
147 sys.exit(0)
|
599
|
148
|
|
149 # select program
|
600
|
150 prog = progs[options.program]
|
599
|
151
|
611
|
152 # start process
|
608
|
153 proc = Process(prog)
|
596
|
154
|
611
|
155 # callback for output processing
|
|
156 def process_output(output):
|
613
|
157 print ('[{}] {}\n{}'.format(proc.runtime(),
|
|
158 output.upper(),
|
|
159 '-==-'*10))
|
611
|
160
|
613
|
161
|
|
162 # LEGACY: output = tempfile.SpooledTemporaryFile()
|
608
|
163 # start = time.time()
|
|
164 # proc = subprocess.Popen(prog, stdout=output)
|
|
165 # location = 0
|
613
|
166
|
|
167 # start the main subprocess loop
|
|
168 # while proc.poll() is None:
|
|
169
|
|
170 # LEGACY:
|
|
171 # curr_time = time.time()
|
|
172 # run_time = curr_time - start
|
|
173 # if run_time > options.time:
|
|
174 # proc.kill()
|
|
175
|
|
176
|
608
|
177 # output.seek(location)
|
|
178 # read = output.read()
|
|
179 # location += len(read)
|
|
180 # print ('[{}] {}\n{}'.format(run_time, read, '-==-'*10))
|
|
181 # if options.sleep:
|
|
182 # time.sleep(options.sleep)
|
|
183
|
|
184 # # reset tempfile
|
|
185 # output.seek(0)
|
596
|
186
|
611
|
187 # wait for being done
|
|
188 proc.wait(maxtime=options.time, sleep=options.sleep, process_output=process_output)
|
|
189
|
|
190 # finalization
|
|
191 output = proc.output
|
|
192 n_lines = len(output.splitlines())
|
596
|
193 print ("{}: {} lines".format(subprocess.list2cmdline(prog), n_lines))
|
|
194
|
|
195 if __name__ == '__main__':
|
|
196 main()
|