The below code tries to run multiple commands in parallel and each command has a timeout. If processing is not completed by timeout it is to be stopped (I am using terminate()).
The issue is after termination (returncode is set to -ve) the communicate() method hangs and when forced exit (Ctrl+C) then following error is displayed.
(stdout, stderr) = proc.communicate()
File "python3.7/subprocess.py", line 926, in communicate
stdout = self.stdout.read()
Code
procList = []
for app in appList:
try:
p = subprocess.Popen(app['command'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
procList.append((app, p))
except Exception as e:
print(e)
start = time.time()
while len(procList):
time.sleep(30)
try:
for app, proc in procList:
if (time.time() - start > app['timeoutSec']):
proc.terminate()
if proc.poll() is not None and app['mailSent'] == 0:
(stdout, stderr) = proc.communicate() #Hangs here is the process is terminated
send_results_mail('Execution Completed or Terminated')
app['mailSent'] = 1
except subprocess.SubprocessError as e:
print(e)
procList = [(app, proc) for (app, proc) in procList if app['mailSent'] == 0]