[英]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我有一个 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)
Main problem i am facing is: even after successfully executing taskkill command, I still have 5 cmd are opened.我面临的主要问题是:即使成功执行 taskkill 命令后,我仍然打开了 5 个 cmd。 Is there any way where we can completely kill/terminate the cmd while it is running?
有什么方法可以在 cmd 运行时完全杀死/终止它?
Under linux I get back the pid of the shell, and the Python processes survive.在 linux 下,我得到了 shell 的 pid,并且 Python 进程仍然存在。
To then get the python code to run without the shell I need to specify the full path name of the python executable:然后要让 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)
works with a slightly changed test.py与稍作改动的 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.
如果它们位于单独的目录中,我预计需要进行一些更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.