簡體   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