[英]Can I close the CMD window that opened with subprocess.Popen in Python?
I have a program that need to run small tasks in new CMDs. 我有一个程序需要在新的CMD中运行小任务。 For example:
例如:
def main()
some code
...
proc = subprocess.Popen("start.bat")
some code...
proc.kill()
subprocess,Popen opens a new cmd window and runs "start.bat" in it. 在子进程中,Popen打开一个新的cmd窗口并在其中运行“start.bat”。 proc.kill() kills the process but doesn't close the cmd window.
proc.kill()终止进程,但不关闭cmd窗口。 Is there a way to close this cmd window?
有没有办法关闭这个cmd窗口?
I thought about naming the opened cmd window so i can kill it with the command: 我想到命名打开的cmd窗口,所以我可以用命令杀死它:
/taskkill /f /im cmdName.exe
Is it possible ?if no, What do you suggest ? 有可能吗?如果没有,你有什么建议?
Edit, Added Minimal, Complete, and Verifiable example: 编辑,添加最小,完整和可验证的示例:
a.py: a.py:
import subprocess,time
proc = subprocess.Popen("c.bat",creationflags=subprocess.CREATE_NEW_CONSOLE)
time.sleep(5)
proc.kill()
b.py b.py
while True:
print("IN")
c.bat C.BAT
python b.py
here is another way you can do it 这是你可以做到的另一种方式
import subprocess
from subprocess import Popen,CREATE_NEW_CONSOLE
command ='cmd'
prog_start=Popen(command,creationflags=CREATE_NEW_CONSOLE)
pidvalue=prog_start.pid
#this will kill the invoked terminal
subprocess.Popen('taskkill /F /T /PID %i' % pidvalue)
that's expected when a subprocess is running. 当子进程正在运行时,这是预期的。 You're just killing the
.bat
process. 你刚刚杀了
.bat
进程。
You can use psutil
(third party, use pip install psutil
to install) to compute the child processes & kill them, like this: 你可以使用
psutil
(第三方,使用pip install psutil
来安装)来计算子进程并杀死它们,如下所示:
import subprocess,time,psutil
proc = subprocess.Popen("c.bat",creationflags=subprocess.CREATE_NEW_CONSOLE)
time.sleep(5)
pobj = psutil.Process(proc.pid)
# list children & kill them
for c in pobj.children(recursive=True):
c.kill()
pobj.kill()
tested with your example, the window closes after 5 seconds 用你的例子测试,窗口在5秒后关闭
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.