w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Best Approach to Threading/Spawning Multiple OS Commands and Getting Output at Various Points

I think you could simplify things by having Command inherit from threading.Thread:

import sys
import subprocess
import threading

cmd = "/path/to/utility -x arg1 -y arg2"

class Command(threading.Thread):
    def __init__(self, cmd):
        super(Command, self).__init__()
        self.cmd = cmd
        self.process = None
        self.returncode = None
        self.jobid = None

    def run(self):
        print "Starting job..."
        self.process = subprocess.Popen(self.cmd, stdout=subprocess.PIPE, 
                                        stderr=subprocess.PIPE, shell=True)
        out, err = self.process.communicate()
        self.jobid = out.split()[10]

    def alive(self):
        if self.process.poll():
            return True
        else:
            return False

    def getJobID(self):
        return self.jobid


job = Command(cmd)
job.start()

if job.alive():
   print "Job is still alive."
else:
   print "Job is not alive."

sys.exit(0)

You can't use self.process.communicate() to get the job id prior to the command actually exiting, becausecommunicate() will block until the program completes. Instead, you'd need to use read directly from the process' stdout:

self.process = subprocess.Popen(self.cmd,
stdout=subprocess.PIPE, 
                                stderr=subprocess.PIPE, bufsize=0,
shell=True)
out = self.process.stdout.readline()
self.jobid = out.split()[10]

Note that bufsize=0 is added, so try to avoid the subprocess buffering its output, which could make readline block.

Then you can call communicate or wait to wait for the process to end:

self.returncode = self.process.wait()




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.