如何使用 python 2.7 关闭 cmd 窗口 [英] How to close a cmd window using python 2.7

查看:61
本文介绍了如何使用 python 2.7 关闭 cmd 窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题几乎说明了这一点,虽然它不需要特定于一个 cmd,只是一般地关闭一个应用程序.我见过

The title pretty much says it, although it does not need to be specific to a cmd, just closing an application in general. I have seen

os.system(taskkill blah blah)

这实际上并没有关闭窗口,而只是在窗口内结束 cmd,我想实际关闭窗口本身.

this does not actually close the windows but rather just ends the cmd inside the window, I would like to actually close the window itself.

有人可以给我一行特定的代码来关闭 cmd 窗口.鼠标悬停时cmd窗口的名称是

Could someone please give me a specific line of code that would close a cmd window. The name of the cmd window when moused over is

C:\Windows\system32\cmd.exe

推荐答案

这是一种使用 Python 的方法Windows 扩展 (pywin32) 以查找 PID 和 taskill结束该过程(基于此示例).我这样做是为了让您可以访问一些额外的运行信息,以防您不想不加选择地杀死任何 cmd.exe:

Here is an approach that uses the Python for Windows extensions (pywin32) to find the PIDs and taskill to end the process (based on this example). I went this way to give you access to some extra running information in case you didn't want to indiscriminately kill any cmd.exe:

import os
from win32com.client import GetObject

WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')

for p in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'):
    print "Killing PID:", p.Properties_('ProcessId').Value
    os.system("taskkill /pid "+str(p.Properties_('ProcessId').Value))

现在在 for 循环中,您可以查看有关每个正在运行的进程的其他一些信息(甚至查找依赖于它的子进程(例如在每个 cmd.exe 中运行的程序).如何读取每个进程属性的示例可能看起来像这样:

Now inside that for loop you could peek at some other information about each running process (or even look for child processes that depend on it (like running programs inside each cmd.exe). An example of how to read each process property might look like this:

from win32com.client import GetObject

WMI = GetObject('winmgmts:')
processes = WMI.InstancesOf('Win32_Process')

for p in WMI.ExecQuery('select * from Win32_Process where Name="cmd.exe"'):
    print "--running cmd.exe---"
    for prop in [prop.Name for prop in p.Properties_]:
        print prop,"=",p.Properties_(prop).Value

这篇关于如何使用 python 2.7 关闭 cmd 窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆