Any way to collect exit status of zombie process in python?

24 Views Asked by At

I have a shell script which runs for more than 10 hours. I have a wrapper Python script which calls the shell script using subprocess.run(). As long as my PuTTY session(I am sshing to linux host) is active, I don't have any issues. Sometimes (because of bad internet connection), the PuTTY session gets terminated and this kills both Python and the shell script.

I have simplified the problem with sample code:

shell script sample.sh

#!/usr/bin/ksh

i=1
while (( i < 10 ))
do 
  timenow=`date '+%d-%m=%y %H:%M:%S'`
  echo $timenow
  (( i = i + 1))
  sleep 3600
done

exit 0

Python script:

import subprocess

cmd = sample.sh 

p = subprocess.run(cmd, text=True, capture_output=True, shell=True)

print(p.stdout.splitline(), p.returncode()) 

Since the run() function waits for child processes to finish, that explains why the shell script is getting killed when the Python script is killed.

I replaced run() with Popen() so that it can run independent of a Python script but I don't have any means to capture output/return code of the shell script. Any way to capture the return code from a zombie child process ?

import subprocess
import time

cmd = ((sample.sh &)&) # --> running script in background 

with subprocss.Popen(cmd, stdout=subprocess.PIPE, stdin=subprocess.PIPE, shell=True) check:
     while check.poll() is None:
           print("script is still running")
           sleep(3500)
     if check.poll():
          print(f"return code is "{check.returncode}") 

I need a way to capture the return code of the shell script.

0

There are 0 best solutions below