operating system - Python subprocess get output as process finishes -
currently getting mac addresses devices via bluetooth , pass these mac addresses 1 @ time method calls subprocess , assigns output variable. variable run filtering functions value command called in subprocess. return value if finds output.
what pass mac addresses method @ once , run them @ 1 time. how capture output of each process , run filtering script processes complete, , @ same time notify me if process fails or errors.
here current method handles 1 mac @ time. lets assume passing list of mac addresses.
def getchan(mac): = subprocess.popen(["sdptool", "search","--bdaddr", mac, "opush"], stdout = subprocess.pipe).communicate()[0].split()[2:] if a==[]: print "error" return "error" else: count = 0 item in a: if item == "channel:": return a[count + 1] count += 1 return "could not find opush channel"
it should like
def getchan(macs): processes = set() mac in macs: processes.add(subprocess.popen(["sdptool", "search","--bdaddr", mac, "opush"], stdout = subprocess.pipe).communicate()[0].split()[2:]) #this need
thank taking look. or clarification of subprocesses appreciated.
import select import subprocess def in_parallel(processes): pipes = {p.stdout.fileno(): (i, p.stdout) i, p in enumerate(processes)} poller = select.poll() fd, pipe in pipes.iteritems(): poller.register(fd, select.pollin) outputs = [''] * len(processes) while pipes: active = poller.poll() fd, event in active: idx, pipe = pipes[fd] o = pipe.read() if o: outputs[idx] += o else: poller.unregister(fd) pipe.close() del pipes[fd] p in processes: p.wait() return outputs args = ['a', 'b', 'c'] processes = [subprocess.popen(['sleep 5; echo ' + arg], stdout=subprocess.pipe, shell=true) arg in args] outputs = in_parallel(processes) print outputs
$ time python test.py ['a\n', 'b\n', 'c\n'] real 0m5.042s user 0m0.016s sys 0m0.016s
Comments
Post a Comment