Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
basictimerapp.py259 linesDownload Raw Back to app
1# basictimerapp - a really simple timer application.2# This should be run using the command line:3# pythonwin /app demos\basictimerapp.py4import sys5import time6 7import timer8import win32api9import win32con10import win32ui11from pywin.framework import app, cmdline, dlgappcore12 13 14class TimerAppDialog(dlgappcore.AppDialog):15    softspace = 116 17    def __init__(self, appName=""):18        dlgappcore.AppDialog.__init__(self, win32ui.IDD_GENERAL_STATUS)19        self.timerAppName = appName20        self.argOff = 021        if len(self.timerAppName) == 0:22            if len(sys.argv) > 1 and sys.argv[1][0] != "/":23                self.timerAppName = sys.argv[1]24                self.argOff = 125 26    def PreDoModal(self):27        # 		sys.stderr = sys.stdout28        pass29 30    def ProcessArgs(self, args):31        for arg in args:32            if arg == "/now":33                self.OnOK()34 35    def OnInitDialog(self):36        win32ui.SetProfileFileName("pytimer.ini")37        self.title = win32ui.GetProfileVal(38            self.timerAppName, "Title", "Remote System Timer"39        )40        self.buildTimer = win32ui.GetProfileVal(41            self.timerAppName, "Timer", "EachMinuteIntervaler()"42        )43        self.doWork = win32ui.GetProfileVal(self.timerAppName, "Work", "DoDemoWork()")44        # replace "\n" with real \n.45        self.doWork = self.doWork.replace("\\n", "\n")46        dlgappcore.AppDialog.OnInitDialog(self)47 48        self.SetWindowText(self.title)49        self.prompt1 = self.GetDlgItem(win32ui.IDC_PROMPT1)50        self.prompt2 = self.GetDlgItem(win32ui.IDC_PROMPT2)51        self.prompt3 = self.GetDlgItem(win32ui.IDC_PROMPT3)52        self.butOK = self.GetDlgItem(win32con.IDOK)53        self.butCancel = self.GetDlgItem(win32con.IDCANCEL)54        self.prompt1.SetWindowText("Python Timer App")55        self.prompt2.SetWindowText("")56        self.prompt3.SetWindowText("")57        self.butOK.SetWindowText("Do it now")58        self.butCancel.SetWindowText("Close")59 60        self.timerManager = TimerManager(self)61        self.ProcessArgs(sys.argv[self.argOff :])62        self.timerManager.go()63        return 164 65    def OnDestroy(self, msg):66        dlgappcore.AppDialog.OnDestroy(self, msg)67        self.timerManager.stop()68 69    def OnOK(self):70        # stop the timer, then restart after setting special boolean71        self.timerManager.stop()72        self.timerManager.bConnectNow = 173        self.timerManager.go()74        return75 76 77# 	def OnCancel(self): default behaviour - cancel == close.78# 		return79 80 81class TimerManager:82    def __init__(self, dlg):83        self.dlg = dlg84        self.timerId = None85        self.intervaler = eval(self.dlg.buildTimer)86        self.bConnectNow = 087        self.bHaveSetPrompt1 = 088 89    def CaptureOutput(self):90        self.oldOut = sys.stdout91        self.oldErr = sys.stderr92        sys.stdout = sys.stderr = self93        self.bHaveSetPrompt1 = 094 95    def ReleaseOutput(self):96        sys.stdout = self.oldOut97        sys.stderr = self.oldErr98 99    def write(self, str):100        s = str.strip()101        if len(s):102            if self.bHaveSetPrompt1:103                dest = self.dlg.prompt3104            else:105                dest = self.dlg.prompt1106                self.bHaveSetPrompt1 = 1107            dest.SetWindowText(s)108 109    def go(self):110        self.OnTimer(None, None)111 112    def stop(self):113        if self.timerId:114            timer.kill_timer(self.timerId)115        self.timerId = None116 117    def OnTimer(self, id, timeVal):118        if id:119            timer.kill_timer(id)120        if self.intervaler.IsTime() or self.bConnectNow:121            # do the work.122            try:123                self.dlg.SetWindowText(self.dlg.title + " - Working...")124                self.dlg.butOK.EnableWindow(0)125                self.dlg.butCancel.EnableWindow(0)126                self.CaptureOutput()127                try:128                    exec(self.dlg.doWork)129                    print("The last operation completed successfully.")130                except:131                    t, v, tb = sys.exc_info()132                    str = "Failed: %s: %s" % (t, repr(v))133                    print(str)134                    self.oldErr.write(str)135                    tb = None  # Prevent cycle136            finally:137                self.ReleaseOutput()138                self.dlg.butOK.EnableWindow()139                self.dlg.butCancel.EnableWindow()140                self.dlg.SetWindowText(self.dlg.title)141        else:142            now = time.time()143            nextTime = self.intervaler.GetNextTime()144            if nextTime:145                timeDiffSeconds = nextTime - now146                timeDiffMinutes = int(timeDiffSeconds / 60)147                timeDiffSeconds = timeDiffSeconds % 60148                timeDiffHours = int(timeDiffMinutes / 60)149                timeDiffMinutes = timeDiffMinutes % 60150                self.dlg.prompt1.SetWindowText(151                    "Next connection due in %02d:%02d:%02d"152                    % (timeDiffHours, timeDiffMinutes, timeDiffSeconds)153                )154        self.timerId = timer.set_timer(155            self.intervaler.GetWakeupInterval(), self.OnTimer156        )157        self.bConnectNow = 0158 159 160class TimerIntervaler:161    def __init__(self):162        self.nextTime = None163        self.wakeUpInterval = 2000164 165    def GetWakeupInterval(self):166        return self.wakeUpInterval167 168    def GetNextTime(self):169        return self.nextTime170 171    def IsTime(self):172        now = time.time()173        if self.nextTime is None:174            self.nextTime = self.SetFirstTime(now)175        ret = 0176        if now >= self.nextTime:177            ret = 1178            self.nextTime = self.SetNextTime(self.nextTime, now)179            # do the work.180        return ret181 182 183class EachAnyIntervaler(TimerIntervaler):184    def __init__(self, timeAt, timePos, timeAdd, wakeUpInterval=None):185        TimerIntervaler.__init__(self)186        self.timeAt = timeAt187        self.timePos = timePos188        self.timeAdd = timeAdd189        if wakeUpInterval:190            self.wakeUpInterval = wakeUpInterval191 192    def SetFirstTime(self, now):193        timeTup = time.localtime(now)194        lst = []195        for item in timeTup:196            lst.append(item)197        bAdd = timeTup[self.timePos] > self.timeAt198        lst[self.timePos] = self.timeAt199        for pos in range(self.timePos + 1, 6):200            lst[pos] = 0201        ret = time.mktime(tuple(lst))202        if bAdd:203            ret = ret + self.timeAdd204        return ret205 206    def SetNextTime(self, lastTime, now):207        return lastTime + self.timeAdd208 209 210class EachMinuteIntervaler(EachAnyIntervaler):211    def __init__(self, at=0):212        EachAnyIntervaler.__init__(self, at, 5, 60, 2000)213 214 215class EachHourIntervaler(EachAnyIntervaler):216    def __init__(self, at=0):217        EachAnyIntervaler.__init__(self, at, 4, 3600, 10000)218 219 220class EachDayIntervaler(EachAnyIntervaler):221    def __init__(self, at=0):222        EachAnyIntervaler.__init__(self, at, 3, 86400, 10000)223 224 225class TimerDialogApp(dlgappcore.DialogApp):226    def CreateDialog(self):227        return TimerAppDialog()228 229 230def DoDemoWork():231    print("Doing the work...")232    print("About to connect")233    win32api.MessageBeep(win32con.MB_ICONASTERISK)234    win32api.Sleep(2000)235    print("Doing something else...")236    win32api.MessageBeep(win32con.MB_ICONEXCLAMATION)237    win32api.Sleep(2000)238    print("More work.")239    win32api.MessageBeep(win32con.MB_ICONHAND)240    win32api.Sleep(2000)241    print("The last bit.")242    win32api.MessageBeep(win32con.MB_OK)243    win32api.Sleep(2000)244 245 246app = TimerDialogApp()247 248 249def t():250    t = TimerAppDialog("Test Dialog")251    t.DoModal()252    return t253 254 255if __name__ == "__main__":256    import demoutils257 258    demoutils.NeedApp()259 
codekingpro/portable-devtools · Team Ai