terminate a python program when it hanged using subprocess python

2024/11/20 4:20:12

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:

  1. when test.py hanged open a new cmd
  2. in new opened cmd run test.py
  3. 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_datet = delta.total_seconds()return divmod(t, 60)[0]  # return minutescmd2 = "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)
Answer

Under linux I get back the pid of the shell, and the Python processes survive.

To then get the python code to run without the shell I need to specify the full path name of the python executable:

# main.py
import datetime
import subprocess
import time
import os
import logging
import sysdef 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# print(f'{file_date=}   {datetime.datetime.now()=}')t = delta.total_seconds()return  t # divmod(t, 60)[0]  # return minutescurrent_dir = os.getcwd()
python_executable = sys.executablecmd2 = f"{python_executable} test.py"logging.basicConfig(filename='test.log', level=logging.DEBUG)
logging.error("test.log touched")b = Nonewhile(True):print(f'{modified_time()=}')time.sleep(.8)if modified_time() >= 2:if b is not None:try:print("killing ", b.pid)b.kill()except Exception as e:print(e.args)breakb = subprocess.Popen(cmd2.split(' '), shell=False)

works with a slightly changed test.py

# test.py
import time
import logging
import oscurrent_dir = os.getcwd()logging.basicConfig(filename=f'{current_dir}/test.log', level=logging.DEBUG)logging.error("test.py started...")time.sleep(1000) # this is so long because it is behaving like test.py is hangedlogging.info("test.py is finished...") # before this line i want to close this terminal

I also made sure the log file gets touched from the launching main.py. I didn't understand the list of pid's so I replaced it with an None initialization of b.

Both files are in the same directory. If they are in separate directories I expect some changes are needed.

Variant starting instance of test.py immediately:

# main.py
import datetime
import subprocess
import time
import os
import logging
import sysdef 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# print(f'{file_date=}   {datetime.datetime.now()=}')t = delta.total_seconds()return  t # divmod(t, 60)[0]  # return minutescurrent_dir = os.getcwd()
python_executable = sys.executablecmd2 = f"{python_executable} test.py"b = subprocess.Popen(cmd2.split(' '), shell=False)while(True):print(f'{modified_time()=}')time.sleep(.8)if modified_time() >= 2:try:print("killing ", b.pid)b.kill()except Exception as e:print(e.args)breakb = subprocess.Popen(cmd2.split(' '), shell=False)
https://en.xdnf.cn/q/119866.html

Related Q&A

causes of Python IOError: [Errno 13] Permission denied

When attempting to write a file, I can get this same error when any of following conditions applies:The file exists and is marked read-only. I dont have write permission for the folder and therefore ca…

Python Invalid Syntax IF statement

Im trying to make a quiz in python but I keep getting invalid syntax errors.#This is for addition questions.if (question=add) <---- That is where i get the error for i in range(0,10):first_number_a…

record a web page using python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 3…

returning a string from askopenfilename() to a entry box

I have seen many postings on the use of askopenfilename(), however I still cant seem to find anything to help me display the full file path in an entry box once I have selected said file. below I have…

Overflow error in Python program

Please help me to understand why this code doesnt work. I know there is something very stupid wrong. This should be an implementation of the fourth order Runge kutta algorithm to solve Lorentz system o…

python login 163 mail server

When I use this script to login the 163 mail server,there is something wrong! My python env is python 2.7.8 Please help me!import imaplibdef open_connect(verbose=False):host = imap.163.comport = 993if …

How to get list of keys that share a value with another key within the same dictionary?

I have a dictionary of unique keys where some keys share the same value. For example:D = {ida:{key:1},idb:{key:2},idc:{key:3},idd:{key:3},ide:{key:4},idf:{key:4},idg:{key:4}}I want a list of keys that…

Sqlite3 Error: near question mark: syntax error [duplicate]

This question already has answers here:Parameterized query binding table name as parameter gives error(3 answers)How to use variables in SQL statement in Python?(5 answers)Closed last year.I am trying…

running bs4 scraper needs to be redefined to enrich the dataset - some issues

got a bs4 scraper that works with selenium - see far below: well - it works fine so far: see far below my approach to fetch some data form the given page: clutch.co/il/it-services To enrich the scrap…

Uploading a file in a embed discord.py (not a image)

Im trying to upload a file directly in a embed, I can upload the file but I dont find the way to put it in the embed. What I want is not displaying the file but uploading it so we can download it, is i…