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
|
601
|
14 class Process(subprocess.Popen):
|
|
15 """why would you name a subprocess object Popen?"""
|
|
16
|
603
|
17 defaults = {'buffsize': 'line buffered'
|
|
18 }
|
|
19
|
601
|
20 def __init__(self, *args, **kwargs):
|
|
21 self.output = tempfile.SpooledTemporaryFile()
|
|
22 subprocess.Popen.__init__(self, *args, **kwargs)
|
602
|
23 # TODO: finish
|
596
|
24
|
|
25 def main(args=sys.argv[1:]):
|
599
|
26 """CLI"""
|
596
|
27
|
600
|
28 # available programs
|
|
29 progs = {'yes': ["yes"],
|
|
30 'ping': ['ping', 'google.com']}
|
|
31
|
|
32
|
599
|
33 # parse command line
|
596
|
34 usage = '%prog [options]'
|
|
35 parser = argparse.ArgumentParser(usage=usage, description=__doc__)
|
|
36 parser.add_argument("-t", "--time", dest="time",
|
599
|
37 type=float, default=4.,
|
|
38 help="seconds to run for")
|
|
39 parser.add_argument("-s", "--sleep", dest="sleep",
|
596
|
40 type=float, default=1.,
|
600
|
41 help="sleep this number of seconds between polling")
|
|
42 parser.add_argument("-p", "--prog", dest='program',
|
|
43 choices=progs.keys(),
|
|
44 help="subprocess to run")
|
|
45 # TODO parser.add_argument("--list-programs", help="list available programs")
|
596
|
46 options = parser.parse_args(args)
|
|
47
|
599
|
48
|
|
49 # select program
|
600
|
50 prog = progs[options.program]
|
599
|
51
|
|
52 # start the main subprocess loop
|
|
53 # TODO -> OO
|
596
|
54 output = tempfile.SpooledTemporaryFile()
|
|
55 start = time.time()
|
|
56 proc = subprocess.Popen(prog, stdout=output)
|
599
|
57 location = 0
|
596
|
58 while proc.poll() is None:
|
599
|
59 curr_time = time.time()
|
|
60 run_time = curr_time - start
|
|
61 if run_time > options.time:
|
596
|
62 proc.kill()
|
599
|
63 if options.sleep:
|
|
64 time.sleep(options.sleep)
|
|
65 output.seek(location)
|
|
66 read = output.read()
|
|
67 location += len(read)
|
|
68 print ('[{}] {}\n{}'.format(run_time, read, '-==-'*10))
|
596
|
69
|
|
70 # reset tempfile
|
|
71 output.seek(0)
|
|
72
|
|
73 n_lines = len(output.read().splitlines())
|
|
74 print ("{}: {} lines".format(subprocess.list2cmdline(prog), n_lines))
|
|
75
|
|
76 if __name__ == '__main__':
|
|
77 main()
|