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