How to close a cmd window using python 2.7

前端 未结 5 956
南方客
南方客 2021-01-15 06:03

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 bla         


        
5条回答
  •  灰色年华
    2021-01-15 06:41

    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))
    

    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
    

提交回复
热议问题