我可以关闭在Python中用subprocess.Popen打开的CMD窗口吗? [英] Can I close the CMD window that opened with subprocess.Popen in Python?
问题描述
我有一个程序,需要在新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()
子进程,Popen打开一个新的cmd窗口并在其中运行 start.bat。
proc.kill()终止进程,但不关闭cmd窗口。
是否可以关闭此cmd窗口?
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?
我考虑过命名打开的cmd窗口,以便可以使用以下命令将其杀死:
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
推荐答案
运行子进程时期望的。您只是在杀死 .bat
过程。
that's expected when a subprocess is running. You're just killing the .bat
process.
您可以使用 psutil
(第三方,使用 pip install psutil
安装)来计算子进程&杀死他们,像这样:
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()
通过您的示例进行测试,该窗口在5秒钟后关闭
tested with your example, the window closes after 5 seconds
这篇关于我可以关闭在Python中用subprocess.Popen打开的CMD窗口吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!