python运行cmd命令后关闭cmd窗口,我可以关闭在Python中用subprocess.Popen打开的CMD窗口吗?...

I have a program that need to run small tasks in new CMDs.

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.

proc.kill() kills the process but doesn't close the cmd window.

Is there a way to close this cmd window?

I thought about naming the opened cmd window so i can kill it with the command:

/taskkill /f /im cmdName.exe

Is it possible ?if no, What do you suggest ?

Edit, Added Minimal, Complete, and Verifiable example:

a.py:

import subprocess,time

proc = subprocess.Popen("c.bat",creationflags=subprocess.CREATE_NEW_CONSOLE)

time.sleep(5)

proc.kill()

b.py

while True:

print("IN")

c.bat

python b.py

解决方案

that's expected when a subprocess is running. You're just killing the .bat process.

You can use psutil (third party, use pip install psutil to install) to compute the child processes & kill them, like this:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值