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
|
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)
|
609
|
32 if not subprocess.mswindows:
|
607
|
33 _kwargs['shell'] = isinstance(command, string)
|
|
34
|
606
|
35 # output buffer
|
|
36 self.output_buffer = tempfile.SpooledTemporaryFile()
|
|
37 self.location = 0
|
610
|
38 self.output = ''
|
606
|
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
|
610
|
60 read = self.read()
|
607
|
61
|
606
|
62 # naptime
|
|
63 if sleep:
|
|
64 time.sleep(sleep)
|
|
65
|
608
|
66 # reset tempfile
|
|
67 output.seek(0)
|
|
68
|
|
69 return self.returncode # set by ``.poll()``
|
606
|
70
|
610
|
71 def read(self):
|
|
72 """read from the output buffer"""
|
|
73 self.output_buffer.seek(self.location)
|
|
74 read = self.output_buffer.read()
|
|
75 self.output += read
|
|
76 self.location += len(read)
|
|
77 return read
|
|
78
|
606
|
79 def commandline(self):
|
|
80 """returns string of command line"""
|
|
81
|
|
82 if isinstance(self.command, string):
|
|
83 return self.command
|
|
84 return subprocess.list2cmdline(self.command)
|
|
85
|
|
86 __str__ = commandline
|
|
87
|
596
|
88
|
|
89 def main(args=sys.argv[1:]):
|
599
|
90 """CLI"""
|
596
|
91
|
600
|
92 # available programs
|
|
93 progs = {'yes': ["yes"],
|
|
94 'ping': ['ping', 'google.com']}
|
|
95
|
|
96
|
599
|
97 # parse command line
|
596
|
98 usage = '%prog [options]'
|
|
99 parser = argparse.ArgumentParser(usage=usage, description=__doc__)
|
|
100 parser.add_argument("-t", "--time", dest="time",
|
599
|
101 type=float, default=4.,
|
|
102 help="seconds to run for")
|
|
103 parser.add_argument("-s", "--sleep", dest="sleep",
|
596
|
104 type=float, default=1.,
|
600
|
105 help="sleep this number of seconds between polling")
|
|
106 parser.add_argument("-p", "--prog", dest='program',
|
606
|
107 choices=progs.keys(), default='ping',
|
600
|
108 help="subprocess to run")
|
606
|
109 parser.add_argument("--list-programs", dest='list_programs',
|
|
110 action='store_true', default=False,
|
|
111 help="list available programs")
|
596
|
112 options = parser.parse_args(args)
|
|
113
|
608
|
114 # list programs
|
|
115 if options.list_programs:
|
|
116 for key in sorted(progs.keys()):
|
|
117 print ('{}: {}'.format(key, subprocess.list2cmdline(progs[key])))
|
610
|
118 sys.exit(0)
|
599
|
119
|
|
120 # select program
|
600
|
121 prog = progs[options.program]
|
599
|
122
|
608
|
123 proc = Process(prog)
|
596
|
124
|
608
|
125 # # start the main subprocess loop
|
|
126 # # TODO -> OO
|
|
127 # output = tempfile.SpooledTemporaryFile()
|
|
128 # start = time.time()
|
|
129 # proc = subprocess.Popen(prog, stdout=output)
|
|
130 # location = 0
|
|
131 # while proc.poll() is None:
|
|
132 # curr_time = time.time()
|
|
133 # run_time = curr_time - start
|
|
134 # if run_time > options.time:
|
|
135 # proc.kill()
|
|
136 # output.seek(location)
|
|
137 # read = output.read()
|
|
138 # location += len(read)
|
|
139 # print ('[{}] {}\n{}'.format(run_time, read, '-==-'*10))
|
|
140 # if options.sleep:
|
|
141 # time.sleep(options.sleep)
|
|
142
|
|
143 # # reset tempfile
|
|
144 # output.seek(0)
|
596
|
145
|
|
146 n_lines = len(output.read().splitlines())
|
|
147 print ("{}: {} lines".format(subprocess.list2cmdline(prog), n_lines))
|
|
148
|
|
149 if __name__ == '__main__':
|
|
150 main()
|