简体   繁体   中英

terminate/close cmd terminal while program is running using subprocess python

I have a main.py which open multiple cmd (subprocess test.py) in loop and will kill the process using taskkill if we have opened more than 2 subprocess from main.py

# 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
    cmd2 = "python test.py"
    for i in range(5):
        b = subprocess.Popen(["start", "/wait", "cmd.exe", "/k", cmd2], shell=True)
        pid_lst.append(b.pid)
        time.sleep(1)
        while len(pid_lst) > 2:
            # pop first element from list
            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)

Main problem i am facing is: even after successfully executing taskkill command, I still have 5 cmd are opened. Is there any way where we can completely kill/terminate the cmd while it is running?

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 sys

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
    # print(f'{file_date=}   {datetime.datetime.now()=}')
    t = delta.total_seconds()
    return  t # divmod(t, 60)[0]  # return minutes


current_dir = os.getcwd()
python_executable = sys.executable

run_test_cmd = f"{python_executable} test.py"

b = subprocess.Popen(run_test_cmd.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)
            break
                
        b = subprocess.Popen(run_test_cmd.split(' '), shell=False)

works with a slightly changed test.py

# test.py
import time
import logging
import os

current_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 hanged

logging.info("test.py is finished...") # before this line i want to close this terminal

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM