2017-06-12 69 views
1

你好我已經寫了一個.pyw腳本來自動重新啓動我的電腦,如果我閒置了幾秒鐘。出於某種原因,該腳本僅爲idleTime返回值0.328,而不是實際計算秒爲空閒的秒數。真的不知道哪裏這個問題在於所以這是我的代碼Python自動重啓電腦

import os 
import datetime 
from ctypes import Structure, windll, c_uint, sizeof, byref 

#Script will automatically restart computer at 4 am unless user 
#hits abort button. 

os.system("start C:/Users/alexa/Desktop/test.txt") 

#checks how long user has been idle for 
class LASTINPUTINFO(Structure): 
    _fields_ = [ 
    ('cbSize', c_uint), 
    ('dwTime', c_uint), 
] 

def get_idle_duration(): 
    lastInputInfo = LASTINPUTINFO() 
    lastInputInfo.cbSize = sizeof(lastInputInfo) 
    windll.user32.GetLastInputInfo(byref(lastInputInfo)) 
    millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime 
    return millis/1000.0 


idleTime = get_idle_duration() 

while(idleTime <= 30): 
    print(idleTime) 
    if(idleTime >= 30): 
     os.system("shutdown") 

回答

2

你永遠不更新idleTime你設置一次,然後執行一個while循環....

0

Pythonista是正確的。此外,您正在返回millis變量除以1000.這將使您的重新啓動執行非常漫長,因爲它將花費比重新設置的持續時間長1000倍的時間。我建議你測試這個程序,而不需要在迴歸中進行劃分,並嘗試5分鐘左右的時間,看看你得到了什麼結果。

1

正如Pythonista說,你沒有更新的蟒蛇時間,但因爲我不能還發布評論我包括解決方案,新的答案


while(True): 
    idleTime = get_idle_duration() 
    print(idleTime) 
    if(idleTime >= 30): 
     os.system("shutdown")

但是消耗的資源是導入時間,並添加好主意

time.sleep(1) 
在while循環結束

所以只檢查一次,第二次......