2013-02-03 29 views
0

我在想如何讓功能每分鐘刷新一次,並檢查它是否打開某個文件。我不知道究竟如何去這一點,但繼承人什麼我找的一個例子:檢查在Python中使用定時刷新打開文件

def timedcheck(): 
    if thisgame.exe is open: 
     print("The Program is Open!") 
    else: 
     print("The Program is closed!") 
     *waits 1 minute* 
     timedcheck() 

我也想劇本刷新功能「高清timedcheck():」每一分鐘,所以它一直在檢查thisgame.exe是否打開。

我已經通過該網站搜索過,所有建議都使用「import win32ui」建議,這樣做會給我一個錯誤。

+0

什麼操作系統?它是否必須是跨平臺解決方案? – mgilson

+0

只是Windows 32&64位 –

回答

0

您可以在time module之間使用睡眠,輸入爲60,檢查間隔1分鐘。您可以暫時打開該文件並在不需要時關閉它。如果文件已經打開,將發生IOError。用異常捕捉錯誤,然後程序會再等一分鐘再重試。

import time 
def timedcheck(): 
    try: 
     f = open('thisgame.exe') 
     f.close() 
     print("The Program is Closed!") 
    except IOError: 
     print("The Program is Already Open!") 
    time.sleep(60) #*program waits 1 minute* 
    timedcheck() 
+0

這涵蓋了如何讓程序等待,謝謝。 但是,我將如何獲得腳本來檢查某個程序是否打開。 –

+0

一個很好的補充是,將使用winsound模塊在揚聲器上發出警報。如果你有興趣,有一個[堆棧溢出這裏](http://stackoverflow.com/a/6537563/1961486)。 – Octipi

3

要重複這個檢查每一分鐘:

def timedcheck(): 
    while True: 
     if is_open("thisgame.exe"): 
      print("The Program is Open!") 
     else: 
      print("The Program is closed!") 
     sleep(60) 

因爲它是一個.exe文件,我認爲用「檢查,如果該文件是打開」你的意思是「是否thisgame.exe」是運行。 psutil應該會有幫助 - 我沒有測試過下面的代碼,所以它可能需要一些調整,但顯示了一般原則。

def is_open(proc_name): 
    import psutil 
    for process in psutil.process_iter(): 
     if proc_name in process.name: 
      return True 
    return False 
+0

ImportError:沒有模塊名爲psutil ... 我真的厭倦了這些不斷導入的錯誤,運行Python27順便說一句。 –

+0

他鏈接了psutil頁面。您必須自己下載並將其作爲Python模塊添加;它不是默認的模塊。 – Anorov

+1

沒有'name.contains()'方法。 'psutil.get_process_list()'已棄用。你可以[使用'process_iter()'代替](http://stackoverflow.com/a/14674690/4279)。 – jfs

0

這裏有@rkd91's answer的變化:

import time 

thisgame_isrunning = make_is_running("thisgame.exe") 

def check(): 
    if thisgame_isrunning(): 
     print("The Program is Open!") 
    else: 
     print("The Program is closed!") 

while True: 
    check() # ignore time it takes to run the check itself 
    time.sleep(60) # may wake up sooner/later than in a minute 

其中make_is_running()

import psutil # 3rd party module that needs to be installed 

def make_is_running(program): 
    p = [None] # cache running process 
    def is_running(): 
     if p[0] is None or not p[0].is_running(): 
      # find program in the process list 
      p[0] = next((p for p in psutil.process_iter() 
         if p.name == program), None) 
     return p[0] is not None 
    return is_running 

要在Windows上的Python 2.7安裝psutil,你可以運行psutil-0.6.1.win32-py2.7.exe