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