python程序中止和恢复_用来中止进程的python脚本(Win32)
用來中止進(jìn)程的python腳本(Win32)
Danny 2007-4-2
緣由:
腳本都是用來解決實際問題的,我最近碰到的問題是這樣的(很羅嗦,只關(guān)心代碼的請建議直接跳過)。天敏電視卡提供了定時錄像的功能,這個功能可以定時開機(jī),錄像完成后自動關(guān)機(jī),照理說功能也已經(jīng)夠用,但錄像結(jié)束后沒有關(guān)閉應(yīng)用這個功能。有時我錄像完成后并不需要關(guān)閉電腦(比如說正在bt下載電影),這時前臺的電視窗口就一直開著,喇叭里面還不停播放電視對白,非常地不必要。于是想寫一個python腳本,定時在每天錄像以后執(zhí)行,用來關(guān)閉電視卡應(yīng)用程序。
網(wǎng)上搜了一下,找到相關(guān)的介紹。
一開始的思路是,根據(jù)exe文件找到進(jìn)程id(類似在任務(wù)管理器里面查找),然后中止進(jìn)程,
最漂亮的方法是用WMI對象找到指定進(jìn)程(見reference 1)。隨后發(fā)現(xiàn),更加體面的中止應(yīng)用的方法是找到應(yīng)用程序的窗口,發(fā)送WM_CLOSE消息,如果失敗(比如提示用戶保存文件等待用戶操作),再用TerminateProcess結(jié)束進(jìn)程,其中要注意,TerminateProcess接受的參數(shù)是句柄,而不是進(jìn)程號。
以下的代碼是用來結(jié)束“記事本”這個應(yīng)用的,
1.
根據(jù)窗口的標(biāo)題找到窗口句柄(EnumWindows,注意,需要用可惡的回調(diào)函數(shù),見windowEnumerationHandler),比如“未標(biāo)題
– 記事本”,字符串匹配末尾的“記事本”可以找到
2.
向窗口發(fā)送WM_CLOSE消息(PostMessage),等待10秒
3.
根據(jù)窗口獲得進(jìn)程id(GetWindowThreadProcessId),試圖強(qiáng)行中止進(jìn)程(如果窗口收到WM_CLOSE消息已經(jīng)關(guān)閉,亦無害)
附代碼killwindow.py
#coding=cp936
import win32api
import win32con
import win32gui
import
win32process
import time
#We are going to use the
win32gui.EnumWindows() function to get our top level window
information. This is one of those nasty functions which wants a
callback function passed to it (consult the docs if you are really
bored). So here's one I made earlier:
def
windowEnumerationHandler(hwnd,
resultList):
'''Pass to win32gui.EnumWindows() to
generate list of window handle, window text tuples.'''
resultList.append((hwnd,
win32gui.GetWindowText(hwnd)))
def
killwindow(hwnd):
threadId, processId =
win32process.GetWindowThreadProcessId(hwnd)
print 'processId = ',
processId
# Ask window nicely to
close
win32gui.PostMessage(hwnd,
win32con.WM_CLOSE, 0, 0)
# Allow some time for app to
close
time.sleep(10)
# If app didn't close, force
close
try:
handle =
win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0,
processId)
if
handle:
print 'handle = ', handle
win32api.TerminateProcess(handle,0)
win32api.CloseHandle(handle)
except Exception,
e:
e
pass
#We can pass this, along a
list to hold the results, into win32gui.EnumWindows(), as
so:
topWindows = []
win32gui.EnumWindows(windowEnumerationHandler,
topWindows)
for i in
topWindows:
if i[1].endswith('記事本'):
print i[0],
i[1]
killwindow(i[0])
References:
總結(jié)
以上是生活随笔為你收集整理的python程序中止和恢复_用来中止进程的python脚本(Win32)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我的世界基岩版开服教程Nukkit篇
- 下一篇: use database 很慢/You