# Tai Sakuma <tai.sakuma@cern.ch>
import os
import subprocess
import collections

##__________________________________________________________________||
class SubprocessRunner(object):
    def __init__(self, pipe = False):
        self.running_procs = collections.deque()
        self.pipe = pipe

    def run(self, taskdir, package_path):

        # run_script = os.path.join(taskdir, 'run.py') # This doesn't work.
                                                       # It contradicts with the document https://docs.python.org/2/library/subprocess.html
                                                       # The program's path needs to be relative to cwd
        run_script = os.path.join('.', 'run.py') # This works

        args = [run_script, package_path]
        proc = subprocess.Popen(
            args,
            stdout = subprocess.PIPE if self.pipe else None,
            stderr = subprocess.PIPE if self.pipe else None,
            cwd = taskdir
        )
        self.running_procs.append(proc)
        return proc.pid

    def wait(self):

        finished_pid = [ ]
        while self.running_procs:
            proc = self.running_procs.popleft()

            stdout, stderr = proc.communicate()
            ## proc.communicate() returns (stdout, stderr) when
            ## self.pipe = True. Otherwise they are (None, None)

            finished_pid.append(proc.pid)

        return finished_pid

    def terminate(self):
        while self.running_procs:
            proc = self.running_procs.popleft()
            proc.terminate()

##__________________________________________________________________||

@@ -1052,16 +1052,92 @@
 t(self):
+%0A        %22%22%22wait until all jobs finish and return a list of pids%0A        %22%22%22
 %0A%0A      
@@ -1150,16 +1150,17 @@
 shed_pid
+s
  = %5B %5D%0A 
@@ -1184,32 +1184,33 @@
 .running_procs:%0A
+%0A
             proc
@@ -1444,16 +1444,17 @@
 shed_pid
+s
 .append(
@@ -1491,16 +1491,17 @@
 shed_pid
+s
 %0A%0A    de

add docstring, rename a variable in wait()