comparison python/multiproc.py @ 599:782dc37492c4

STUB: python/multiproc.py
author Jeff Hammel <k0scist@gmail.com>
date Thu, 30 Jan 2014 12:45:45 -0800
parents c5537e841c78
children a77f7022cc06
comparison
equal deleted inserted replaced
598:e21c49e32b95 599:782dc37492c4
9 import subprocess 9 import subprocess
10 import sys 10 import sys
11 import time 11 import time
12 import tempfile 12 import tempfile
13 13
14 here = os.path.dirname(os.path.realpath(__file__)) 14 progs = {'yes': ["yes"],
15 prog = ["yes"] 15 'ping': ['ping', 'google.com']}
16 timeout = 4.
17 sleep = 1.
18 16
19 def main(args=sys.argv[1:]): 17 def main(args=sys.argv[1:]):
18 """CLI"""
20 19
20 # parse command line
21 usage = '%prog [options]' 21 usage = '%prog [options]'
22 parser = argparse.ArgumentParser(usage=usage, description=__doc__) 22 parser = argparse.ArgumentParser(usage=usage, description=__doc__)
23 parser.add_argument("-t", "--time", dest="time", 23 parser.add_argument("-t", "--time", dest="time",
24 type=float, default=4.,
25 help="seconds to run for")
26 parser.add_argument("-s", "--sleep", dest="sleep",
24 type=float, default=1., 27 type=float, default=1.,
25 help="seconds to run for") 28 help="")
26 options = parser.parse_args(args) 29 options = parser.parse_args(args)
27 30
31
32 # select program
33 prog = progs['ping']
34
35 # start the main subprocess loop
36 # TODO -> OO
28 output = tempfile.SpooledTemporaryFile() 37 output = tempfile.SpooledTemporaryFile()
29 start = time.time() 38 start = time.time()
30 proc = subprocess.Popen(prog, stdout=output) 39 proc = subprocess.Popen(prog, stdout=output)
40 location = 0
31 while proc.poll() is None: 41 while proc.poll() is None:
32 if time.time() - start > options.time: 42 curr_time = time.time()
43 run_time = curr_time - start
44 if run_time > options.time:
33 proc.kill() 45 proc.kill()
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))
34 52
35 # reset tempfile 53 # reset tempfile
36 output.seek(0) 54 output.seek(0)
37 55
38 n_lines = len(output.read().splitlines()) 56 n_lines = len(output.read().splitlines())