How to capture stdout of a popen in threading.Thread. I need to parse the stdout for a success message. I am using the below code block to run a command but kill it after timeout_sec seconds. The examples I saw online suggested using
std, err = popen.communicate()
but this is not working since communicate is used in Thread. My knowledge in python thread is very basic. Kindly help.
def run_command_with_timeout(cmd, timeout_sec):
args = shlex.split(str(cmd))
proc = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
proc_thread = Thread(target=proc.communicate)
proc_thread.start()
# for line in proc.stdout:
# print (line)
proc_thread.join(timeout_sec)
# while True:
# line = proc.stdout.readline()
# print line.strip()
# if not line:
# break
if proc_thread.is_alive():
try:
proc.kill()
except OSError, e:
return proc.returncode
return 137
return proc.returncode