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