繁体   English   中英

使用子进程 python 运行程序时终止/关闭 cmd 终端

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

我有一个 main.py,它在循环中打开多个 cmd(子进程 test.py),如果我们从 main.py 打开了两个以上的子进程,将使用 taskkill 杀死进程

# 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)

我面临的主要问题是:即使成功执行 taskkill 命令后,我仍然打开了 5 个 cmd。 有什么方法可以在 cmd 运行时完全杀死/终止它?

在 linux 下,我得到了 shell 的 pid,并且 Python 进程仍然存在。

然后要让 python 代码在没有 shell 的情况下运行,我需要指定 python 可执行文件的完整路径名:

# 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)

与稍作改动的 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

两个文件都在同一个目录中。 如果它们位于单独的目录中,我预计需要进行一些更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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