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
|
|
20 defaults = {'buffsize': 1, # line buffered
|
603
|
21 }
|
|
22
|
606
|
23 def __init__(self, command, **kwargs):
|
|
24
|
|
25 # setup arguments
|
|
26 self.command = command
|
|
27 _kwargs = self.defaults.copy()
|
|
28 _kwargs.update(kwargs)
|
|
29
|
607
|
30 # on unix, ``shell={True|False}`` should always come from the
|
|
31 # type of command (string or list)
|
|
32 if not mswindows:
|
|
33 _kwargs['shell'] = isinstance(command, string)
|
|
34
|
606
|
35 # output buffer
|
|
36 self.output_buffer = tempfile.SpooledTemporaryFile()
|
|
37 self.location = 0
|
|
38 self.output = []
|
|
39 _kwargs['stdout'] = self.output_buffer
|
|
40
|
|
41 # launch subprocess
|
|
42 self.start = time.time()
|
607
|
43 subprocess.Popen.__init__(self, command, **_kwargs)
|
606
|
44
|
|
45 def wait(self, maxtime=None, sleep=1.):
|
|
46 """
|
|
47 maxtime -- timeout in seconds
|
|
48 sleep -- number of seconds to sleep between polling
|
|
49 """
|
|
50 while self.poll() is None:
|
|
51
|
|
52 # check for timeout
|
|
53 curr_time = time.time()
|
|
54 run_time = curr_time - self.start
|
|
55 if run_time > maxtime:
|
|
56 # TODO: read from output
|
|
57 return process.kill()
|
|
58
|
607
|
59 # read from output buffer
|
|
60 self.output_buffer.seek(self.location)
|
|
61 read = self.output_buffer.read()
|
|
62 self.location += len(read)
|
|
63
|
606
|
64 # naptime
|
|
65 if sleep:
|
|
66 time.sleep(sleep)
|
|
67
|
|
68
|
|
69 def commandline(self):
|
|
70 """returns string of command line"""
|
|
71
|
|
72 if isinstance(self.command, string):
|
|
73 return self.command
|
|
74 return subprocess.list2cmdline(self.command)
|
|
75
|
|
76 __str__ = commandline
|
|
77
|
596
|
78
|
|
79 def main(args=sys.argv[1:]):
|
599
|
80 """CLI"""
|
596
|
81
|
600
|
82 # available programs
|
|
83 progs = {'yes': ["yes"],
|
|
84 'ping': ['ping', 'google.com']}
|
|
85
|
|
86
|
599
|
87 # parse command line
|
596
|
88 usage = '%prog [options]'
|
|
89 parser = argparse.ArgumentParser(usage=usage, description=__doc__)
|
|
90 parser.add_argument("-t", "--time", dest="time",
|
599
|
91 type=float, default=4.,
|
|
92 help="seconds to run for")
|
|
93 parser.add_argument("-s", "--sleep", dest="sleep",
|
596
|
94 type=float, default=1.,
|
600
|
95 help="sleep this number of seconds between polling")
|
|
96 parser.add_argument("-p", "--prog", dest='program',
|
606
|
97 choices=progs.keys(), default='ping',
|
600
|
98 help="subprocess to run")
|
606
|
99 parser.add_argument("--list-programs", dest='list_programs',
|
|
100 action='store_true', default=False,
|
|
101 help="list available programs")
|
596
|
102 options = parser.parse_args(args)
|
|
103
|
599
|
104
|
|
105 # select program
|
600
|
106 prog = progs[options.program]
|
599
|
107
|
|
108 # start the main subprocess loop
|
|
109 # TODO -> OO
|
596
|
110 output = tempfile.SpooledTemporaryFile()
|
|
111 start = time.time()
|
|
112 proc = subprocess.Popen(prog, stdout=output)
|
599
|
113 location = 0
|
596
|
114 while proc.poll() is None:
|
599
|
115 curr_time = time.time()
|
|
116 run_time = curr_time - start
|
|
117 if run_time > options.time:
|
596
|
118 proc.kill()
|
599
|
119 output.seek(location)
|
|
120 read = output.read()
|
|
121 location += len(read)
|
|
122 print ('[{}] {}\n{}'.format(run_time, read, '-==-'*10))
|
606
|
123 if options.sleep:
|
|
124 time.sleep(options.sleep)
|
596
|
125
|
|
126 # reset tempfile
|
|
127 output.seek(0)
|
|
128
|
|
129 n_lines = len(output.read().splitlines())
|
|
130 print ("{}: {} lines".format(subprocess.list2cmdline(prog), n_lines))
|
|
131
|
|
132 if __name__ == '__main__':
|
|
133 main()
|