I have a main.py which open a new cmd (subprocess) when another program (test.py, in same directory) is hanged. To determining test.py is hanged or not, I used latest modified time (os.path.getmtime(test.log)) log file, test.log (test.py is continuously writing lines to this test.log file)
Now I have few things to to:
- when test.py hanged open a new cmd
- in new opened cmd run test.py
- kill cmd when we opened more than 2 cmd
# test.py
import time
print("test.py started...")
time.sleep(1000) # this is so long because it is behaving like test.py is hanged
print("test.py is finished...") # before this line i want to close this terminal
# main.py
import datetime
import shelx
import subprocess
def modified_time():
file_date = time.ctime(os.path.getmtime('test.log'))
file_date = datetime.datetime.strptime(file_date, "%a %b %d %H:%M:%S %Y")
delta = datetime.datetime.now() - file_date
t = delta.total_seconds()
return divmod(t, 60)[0] # return minutes
cmd2 = "python test.py"
while(True):
if modified_time() >= 2:
b = subprocess.Popen(["start", "/wait", "cmd.exe", "/k", cmd2], shell=True)
(output, err) = b.communicate()
# b.wait()
pid_lst.append(b.pid)
print(pid_lst)
while len(pid_lst) > 2:
x = pid_lst.pop(0)
#cmd_2 = f"WMIC PROCESS WHERE \"ProcessID={str(x)}\" CALL TERMINATE"
cmd_2 = f"taskkill /PID {str(x)} /F"
args = shlex.split(cmd_2)
try:
y = subprocess.Popen(args, shell=False)
print("killed ", x)
except Exception as e:
print(e.args)