漫漫長假一個人無聊得很,整日DOTA,打的腰酸背痛腿抽筋的.就想着寫一個腳本記錄自己每天打游戲的時間,於是就產生了下面的這個東西...
運行環境:win7 32位.
python版本:3.4.1
由於用到了一些win32api,這些並非python標准庫自帶的,所以你需要先去下載pywin32模塊.去http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/找到對應你的系統及python版本的包,一路next安裝即可.
#coding=gbk import win32com.client import time import os def IsExsit(processName): WMI = win32com.client.GetObject('winmgmts:') processCodeCov = WMI.ExecQuery( 'select * from Win32_Process where Name="%s"' % processName) if len(processCodeCov) > 0: return 1 else: return 0 oldStatus = 0 newStatus = 0 #0代表進程不存在.1代表存在 totalTime = 0 def ShutDown(fp): cmd = "cmd.exe /k shutdown -s -t 0" structTime = time.localtime(time.time()) currentTime = time.strftime('%Y-%m-%d %H:%M:%S', structTime) info = "關機:" + currentTime + "\n" fp.write(info) os.system(cmd) def Handle(processName,fp): global oldStatus, newStatus,totalTime newStatus = IsExsit(processName) structTime = time.localtime(time.time()) currentTime = time.strftime('%Y-%m-%d %H:%M:%S', structTime) print(oldStatus, newStatus,currentTime) #更新進程運行總時間. if newStatus == 1: totalTime += 60 if totalTime >= 60*60*3: #超過3小時則關機 ShutDown(fp) #在進程狀態改變時記錄到文件中 if (oldStatus != newStatus): oldStatus = newStatus structTime = time.localtime(time.time()) strTime = time.strftime('%Y-%m-%d %H:%M:%S', structTime) if newStatus: strTmp = processName + "開啟" else: strTmp = processName + "關閉" info = strTime + "********" + strTmp + "\n" fp.write(info) #fp.close() else: # pass if __name__ == '__main__': fp = open("records.txt", "a+") structTime = time.localtime(time.time()) currentTime = time.strftime('%Y-%m-%d %H:%M:%S', structTime) info = "開始監控:" + currentTime + "\n" fp.write(info) while True: Handle('war3.exe',fp) #5分鍾檢測一次 time.sleep(60)
程序很簡單,隔一段時間監測一下war3.exe進程在不在,在進程狀態有改變時記錄到一個文本中,舉個例子,你8:00的時候把腳本運行起來了,然后9:00你開始玩dota一直到9:30.那么程序在9:00附近監測的時候發現war3.exe從無到有了,那么就會記錄下來寫到recorder.txt中,9:30附近監測到war3.exe從有到無,也會寫到文本中.在腳本運行的過程中,發現war3.exe在運行的話就會開始總時間的統計,當超過3小時,就會執行一個關機命令(好幾把dota打的正爽的時候關機了。。。。。。)
目前腳本做的還不是很完善,比如沒有去捕獲在cmd命令行中鍵入ctrl+z產生的信號,也沒有把監測的進程名稱,間隔時間什么的做到配置文件里去,其實做起來也不復雜,就是人比較懶,不想去弄了....
后續的話考慮用tkinter寫個界面出來,然后再看看加一個短信通知的功能神馬的,暫時把目標寫在這里,希望不要爛尾吧.