Reputation: 491
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)
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.
EDIT: 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
Upvotes: 3
Views: 26089
Reputation: 51
I used this to terminate and close the cmd window, hope it help os.system("taskkill /f /im cmd.exe")
Upvotes: 5
Reputation: 3960
For anyone who's stuck with Python 2.7 and unable to download pywin32 thanks to red tape in your organization. If you're on Windows XP and above you can use taskkill to kill the process by window title name like below for a dos command prompt that was started in elevated mode with title MyTitle
os.system('taskkill /fi "WindowTitle eq Administrator: MyTitle"')
Upvotes: 4
Reputation: 1
the exit() command works however in 2.7 it still asks you if you are sure you want to quit. It states that the program is still running. ETC
Upvotes: -1
Reputation: 30416
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
Upvotes: 2
Reputation: 8045
something like this?
import sys
sys.exit()
or easier ...
raise SystemExit
if that's not what your looking for tell me
also you can just save the file with a .pyw and that doesn't open the cmd at all
Upvotes: 5