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