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