我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用win32api.Sleep()。
def RestartService(serviceName, args = None, waitSeconds = 30, machine = None): "Stop the service, and then start it again (with some tolerance for allowing it to stop.)" try: StopService(serviceName, machine) except pywintypes.error, exc: # Allow only "service not running" error if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE: raise # Give it a few goes, as the service may take time to stop for i in range(waitSeconds): try: StartService(serviceName, args, machine) break except pywintypes.error, exc: if exc.winerror!=winerror.ERROR_SERVICE_ALREADY_RUNNING: raise win32api.Sleep(1000) else: print "Gave up waiting for the old service to stop!"
def TestWord8(word): word.Visible = 1 doc = word.Documents.Add() wrange = doc.Range() for i in range(10): wrange.InsertAfter("Hello from Python %d\n" % i) paras = doc.Paragraphs for i in range(len(paras)): p = paras[i]() p.Font.ColorIndex = i+1 p.Font.Size = 12 + (4 * i) # XXX - note that # for para in paras: # para().Font... # doesnt seem to work - no error, just doesnt work # Should check if it works for VB! doc.Close(SaveChanges = 0) word.Quit() win32api.Sleep(1000) # Wait for word to close, else we # may get OA error.
def ThreadedDemo(): rect = win32ui.GetMainFrame().GetMDIClient().GetClientRect() rect = rect[0], int(rect[3]*3/4), int(rect[2]/4), rect[3] incr = rect[2] for i in range(4): if i==0: f = FontFrame() title = "Not threaded" else: f = ThreadedFontFrame() title = "Threaded GUI Demo" f.Create(title, rect) rect = rect[0] + incr, rect[1], rect[2]+incr, rect[3] # Givem a chance to start win32api.Sleep(100) win32ui.PumpWaitingMessages()
def RestartService(serviceName, args = None, waitSeconds = 30, machine = None): "Stop the service, and then start it again (with some tolerance for allowing it to stop.)" try: StopService(serviceName, machine) except pywintypes.error as exc: # Allow only "service not running" error if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE: raise # Give it a few goes, as the service may take time to stop for i in range(waitSeconds): try: StartService(serviceName, args, machine) break except pywintypes.error as exc: if exc.winerror!=winerror.ERROR_SERVICE_ALREADY_RUNNING: raise win32api.Sleep(1000) else: print("Gave up waiting for the old service to stop!")
def TestWord8(word): word.Visible = 1 doc = word.Documents.Add() wrange = doc.Range() for i in range(10): wrange.InsertAfter("Hello from Python %d\n" % i) paras = doc.Paragraphs for i in range(len(paras)): paras[i]().Font.ColorIndex = i+1 paras[i]().Font.Size = 12 + (4 * i) # XXX - note that # for para in paras: # para().Font... # doesnt seem to work - no error, just doesnt work # Should check if it works for VB! doc.Close(SaveChanges = 0) word.Quit() win32api.Sleep(1000) # Wait for word to close, else we # may get OA error.
def WaitForServiceStatus(serviceName, status, waitSecs, machine=None): """Waits for the service to return the specified status. You should have already requested the service to enter that state""" for i in range(waitSecs*4): now_status = QueryServiceStatus(serviceName, machine)[1] if now_status == status: break win32api.Sleep(250) else: raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "QueryServiceStatus", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
def __StopServiceWithTimeout(hs, waitSecs = 30): try: status = win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP) except pywintypes.error, exc: if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE: raise for i in range(waitSecs): status = win32service.QueryServiceStatus(hs) if status[1] == win32service.SERVICE_STOPPED: break win32api.Sleep(1000) else: raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
def TestExplorer(iexplore): if not iexplore.Visible: iexplore.Visible = -1 iexplore.Navigate(win32api.GetFullPathName('..\\readme.htm')) win32api.Sleep(1000) TestObjectFromWindow() win32api.Sleep(3000) try: iexplore.Quit() except (AttributeError, pythoncom.com_error): # User got sick of waiting :) pass
def TestAll(): try: try: iexplore = win32com.client.dynamic.Dispatch("InternetExplorer.Application") TestExplorer(iexplore) win32api.Sleep(1000) iexplore = None # Test IE events. TestExplorerEvents() # Give IE a chance to shutdown, else it can get upset on fast machines. time.sleep(2) # Note that the TextExplorerEvents will force makepy - hence # this gencache is really no longer needed. from win32com.client import gencache gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) iexplore = win32com.client.Dispatch("InternetExplorer.Application") TestExplorer(iexplore) except pythoncom.com_error, exc: if exc.hresult!=winerror.RPC_E_DISCONNECTED: # user closed the app! raise finally: iexplore = None
def log(self, msg): servicemanager.LogInfoMsg(str(msg)) def sleep(self, sec): win32api.Sleep(sec * 1000, True)
def _input_left_mouse(self, x, y): left, top, right, bottom = self.rect width, height = right - left, bottom - top if x < 0 or x > width or y < 0 or y > height: return win32gui.SetForegroundWindow(self.hwnd) pos = win32gui.GetCursorPos() win32api.SetCursorPos((left+x, top+y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0) win32api.Sleep(100) #ms win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0) win32api.Sleep(100) #ms # win32api.SetCursorPos(pos)
def kill(self, gracePeriod=5000): """ Kill process. Try for an orderly shutdown via WM_CLOSE. If still running after gracePeriod (5 sec. default), terminate. """ win32gui.EnumWindows(self.__close__, 0) if self.wait(gracePeriod) != win32event.WAIT_OBJECT_0: win32process.TerminateProcess(self.hProcess, 0) win32api.Sleep(100) # wait for resources to be released
def CallPipe(fn, args): ret = None retryCount = 0 while retryCount < 8: # Keep looping until user cancels. retryCount = retryCount + 1 try: return fn(*args) except win32api.error, exc: if exc.winerror==winerror.ERROR_PIPE_BUSY: win32api.Sleep(5000) continue else: raise raise RuntimeError("Could not make a connection to the server")
def thread_test(o): for i in range(5): o.write("Hi from thread %d\n" % (win32api.GetCurrentThreadId())) win32api.Sleep(100)
def test(): w = WindowOutput(queueing=flags.WQ_IDLE) w.write("First bit of text\n") import _thread for i in range(5): w.write("Hello from the main thread\n") _thread.start_new(thread_test, (w,)) for i in range(2): w.write("Hello from the main thread\n") win32api.Sleep(50) return w
def demo(): d = StatusProgressDialog("A Demo", "Doing something...") import win32api for i in range(100): if i == 50: d.SetText("Getting there...") if i==90: d.SetText("Nearly done...") win32api.Sleep(20) d.Tick() d.Close()
def DoDemoWork(): print "Doing the work..." print "About to connect" win32api.MessageBeep(win32con.MB_ICONASTERISK) win32api.Sleep(2000) print "Doing something else..." win32api.MessageBeep(win32con.MB_ICONEXCLAMATION) win32api.Sleep(2000) print "More work." win32api.MessageBeep(win32con.MB_ICONHAND) win32api.Sleep(2000) print "The last bit." win32api.MessageBeep(win32con.MB_OK) win32api.Sleep(2000)
def Test(): num=1 while num<1000: print 'Hello there no ' + str(num) win32api.Sleep(50) num = num + 1
def thread_demo(): d = ThreadedStatusProgressDialog("A threaded demo", "Doing something") import win32api for i in range(100): if i == 50: d.SetText("Getting there...") if i==90: d.SetText("Nearly done...") win32api.Sleep(20) d.Tick() d.Close()
def DoDemoWork(): print("Doing the work...") print("About to connect") win32api.MessageBeep(win32con.MB_ICONASTERISK) win32api.Sleep(2000) print("Doing something else...") win32api.MessageBeep(win32con.MB_ICONEXCLAMATION) win32api.Sleep(2000) print("More work.") win32api.MessageBeep(win32con.MB_ICONHAND) win32api.Sleep(2000) print("The last bit.") win32api.MessageBeep(win32con.MB_OK) win32api.Sleep(2000)
def Test(): num=1 while num<1000: print('Hello there no ' + str(num)) win32api.Sleep(50) num = num + 1
def __StopServiceWithTimeout(hs, waitSecs = 30): try: status = win32service.ControlService(hs, win32service.SERVICE_CONTROL_STOP) except pywintypes.error as exc: if exc.winerror!=winerror.ERROR_SERVICE_NOT_ACTIVE: raise for i in range(waitSecs): status = win32service.QueryServiceStatus(hs) if status[1] == win32service.SERVICE_STOPPED: break win32api.Sleep(1000) else: raise pywintypes.error(winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService", win32api.FormatMessage(winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
def TestAll(): try: try: iexplore = win32com.client.dynamic.Dispatch("InternetExplorer.Application") TestExplorer(iexplore) win32api.Sleep(1000) iexplore = None # Test IE events. TestExplorerEvents() # Give IE a chance to shutdown, else it can get upset on fast machines. time.sleep(2) # Note that the TextExplorerEvents will force makepy - hence # this gencache is really no longer needed. from win32com.client import gencache gencache.EnsureModule("{EAB22AC0-30C1-11CF-A7EB-0000C05BAE0B}", 0, 1, 1) iexplore = win32com.client.Dispatch("InternetExplorer.Application") TestExplorer(iexplore) except pythoncom.com_error as exc: if exc.hresult!=winerror.RPC_E_DISCONNECTED: # user closed the app! raise finally: iexplore = None
def sleep(self, sec): win32api.Sleep(sec*1000, True)
def shortcut_keys(self,list_key=[],time=5): for x in list_key: tmp = self.dic_keycode(x) win32api.keybd_event(tmp,0,0,0) win32api.Sleep(time) for x in list_key: tmp = self.dic_keycode(x) win32api.keybd_event(tmp,0,win32con.KEYEVENTF_KEYUP,0) win32api.Sleep(time) return True #Click Current Place
def wpkggp_query(filter, blacklist): msg = 'Query' error_msg = None packages = [] try: pipeHandle = CreateFile("\\\\.\\pipe\\WPKG", GENERIC_READ | GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None) except pywintypes.error, (n, f, e): # print "Error when generating pipe handle: %s" % e error_msg = u"Error: WPKG-GP Service not running" return error_msg SetNamedPipeHandleState(pipeHandle, PIPE_READMODE_MESSAGE, None, None) WriteFile(pipeHandle, msg) n = 0 while 1: try: (hr, readmsg) = ReadFile(pipeHandle, 512) out = readmsg[4:].decode('utf-8') # Strip 3 digit status code and decode status_code = int(readmsg[:3]) if status_code == 103: # query output for x in ['TASK: ', 'NAME: ', 'REVISION: ']: out = out.replace(x, '') package = out.split('\t') # Filter Packages by task if package[0] in filter: # Filter Packages by name if not package[1].lower().startswith(blacklist): packages.append(package) elif status_code == 104: # No pending updates continue elif status_code > 200: # errors if status_code == 203: error_msg = 'Error: Query function not supported in the installed wpkg-gp version.' else: error_msg = out except win32api.error as exc: if exc.winerror == winerror.ERROR_PIPE_BUSY: win32api.Sleep(5000) print 'Pipe Busy Error' continue break if error_msg: return error_msg else: # Sort list by installs, updates, downgrades and removes sort_order = {"install": 0, "update": 1, "downgrade": 2, "remove": 3} packages.sort(key=lambda val: sort_order[val[0]]) return packages
def Onu_login(self,FlowName): print 'onu_login fuction' if self.Onu_login_Flag == 1 : return True ap_name = FlowName.split('_')[-1] if ap_name =='ONU': login_username = LOGIN_USERNAME_GONGJIN login_password = LOGIN_PASSWORD_GONGJIN print 'GONGJIN:login_username--',login_username print 'GONGJIN:login_password--',login_password test_win = win_gui() hwnd = win32gui.FindWindow('#32770',None) print 'hwnd is ',hwnd if hwnd < 1: log_public(WEB_ERR_NO_0020) self.m_ERROR_MSG = WEB_ERR_NO_0020 return False else: win32api.Sleep(100) win32api.keybd_event(18,0,0,0); win32api.keybd_event(85,0,0,0); win32api.Sleep(100) win32api.keybd_event(85,0,win32con.KEYEVENTF_KEYUP,0); win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(100) shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys(login_username) win32api.Sleep(100) win32api.keybd_event(18,0,0,0); win32api.keybd_event(80,0,0,0); win32api.Sleep(100) win32api.keybd_event(80,0,win32con.KEYEVENTF_KEYUP,0); win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(300) shell.SendKeys(login_password) win32api.Sleep(100) win32api.keybd_event(13,0,0,0); win32api.Sleep(100) win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(100) return True
def check_Landdlg(self,hwdlist,lst_t=[]): try: for x in hwdlist: title_name= win32gui.GetWindowText(x) #print 'here',title_name if title_name.startswith('?')==True: #app.connect_(handle=x) #print '11111' username='admin' passwd ='admin' if len(lst_t)!=0: for y in lst_t: print 'lstSub[j]333332222215:' ,y if y.has_key('ASSIST')==True: if y['ASSIST'] == KEY_USERNAME: username = y['ControlType'] elif y['ASSIST'] == KEY_PASSWD: passwd = y['ControlType'] Editlist = findControls(topHwnd=x,wantedClass='Edit') print 'Editlist:',Editlist print 'passwd:',passwd,' username:',username userFlag = False tmp_hwd =[] for y in Editlist: print '2222',y, ' getEditText(y):',getEditText(y) if y in tmp_hwd: continue else: tmp_hwd.append(y) if len(getEditText(y))>1: print 'getEditText(y)',getEditText(y) , ' len:',len(getEditText(y)) continue if userFlag==False: setEditText(y,username) else: setEditText(y,passwd) userFlag = True win32api.Sleep(100) #time.sleep(100) b_hwd = findControl(topHwnd=x,wantedClass='Button',wantedText='?') #print 'button',b_hwd clickButton(b_hwd) except Exception ,exc_str: log_print(exc_str) return False return True
def choose_conf_file(self): #get control of waveQoE window. hwnd3 = win32gui.FindWindow(WAVEQOE_CLASS,None) print 'hwnd3',hwnd3 time.sleep(0.5) #set waveQoE window to top. win32gui.SetForegroundWindow(hwnd3) time.sleep(0.5) #move waveQoE window to top left corner. win32gui.MoveWindow(hwnd3,0,0,1448,878,1) #send Alt+F to open 'File' in menu bar. win32api.Sleep(1000) win32api.keybd_event(18,0,0,0); #18Alt? win32api.keybd_event(70,0,0,0); #70F? win32api.Sleep(1000) win32api.keybd_event(70,0,win32con.KEYEVENTF_KEYUP,0); win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(1000) #send O to open 'open' window. win32api.keybd_event(79,0,0,0); #79O? win32api.Sleep(1000) win32api.keybd_event(79,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(1000) #choose config file and open it. self.myobj.Find_Gui_edit(str_app = 'Open',control_class = 'ComboBox',filename = self.conf_file_dir,control_name = '',stop_flag = '0') self.myobj.Find_Gui_button(str_app = 'Open',control_class = 'Button',control_name = '(&O)') time.sleep(0.5) hwnd4 = win32gui.FindWindow('#32770','Open') print 'hwnd4: ',hwnd4 if hwnd4 > 0: log_public(ERR_NO_0006) self.m_ERROR_MSG = ERR_NO_0006 self.myobj.Find_Gui_button(str_app = 'Open',control_class = 'Button',control_name = '?') time.sleep(0.5) self.myobj.Find_Gui_button(str_app = 'Open',control_class = 'Button',control_name = '?') time.sleep(0.5) self.close_waveQoE() print 'close_waveqoe' return False else: print 'conf_file is correct.' return True #----------------------------------------------------------------------------- # Name: Mouse_LB_click # purpose: click the mouse's left butten. # explain: # Author: yuanwen # # Created: 2013/07/5 #-----------------------------------------------------------------------------
def close_waveQoE(self): #get the handle of waveQoE window. try: hwnd6 = win32gui.FindWindow(WAVEQOE_CLASS,None) print 'hwnd6:',hwnd6 time.sleep(1) #set the waveQoE window to the top. win32gui.SetForegroundWindow(hwnd6) time.sleep(1) except: print 'close error' log_public(ERR_NO_0009) self.m_ERROR_MSG = ERR_NO_0009 return False #click the title bar. self.myobj.Mouse_LB_D(str_app = WAVEQOE_CLASS,lb_dx = '75',lb_dy = '10',Flag = '1') #send Alt+F to open 'File' in menu bar. win32api.Sleep(1000) win32api.keybd_event(18,0,0,0); #18Alt? win32api.keybd_event(70,0,0,0); #70F? win32api.Sleep(1000) win32api.keybd_event(70,0,win32con.KEYEVENTF_KEYUP,0); win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(1000) #send X to close waveQoE window. win32api.keybd_event(88,0,0,0); #88X? win32api.Sleep(1000) win32api.keybd_event(88,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(1000) if self.timeout == 1: #send Alt+Y to exit waveQoE without save. win32api.keybd_event(18,0,0,0); #18Alt? win32api.keybd_event(89,0,0,0); #89Y? win32api.Sleep(1000) win32api.keybd_event(89,0,win32con.KEYEVENTF_KEYUP,0); win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(1000) else: #send Alt+N to exit waveQoE without save. win32api.keybd_event(18,0,0,0); #18Alt? win32api.keybd_event(78,0,0,0); #78N? win32api.Sleep(1000) win32api.keybd_event(78,0,win32con.KEYEVENTF_KEYUP,0); win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(1000) return True
def first_test_case(self,test_case = r"E:\UFTTestCase\EMS_Test\EMS_FUN_000012\DemoTest\DemoTest"): WINDOW_TITLE = u'HP Unified Functional Testing' self.app[WINDOW_TITLE].TypeKeys(u'^O') time.sleep(2) try: shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys(test_case) except Exception,e: print e time.sleep(2) self.app[u'Open Test'][u'Open'].Click() test_win = win_gui() cnt = 0 while cnt<60: try: hwnd = 0 hwnd = test_win.find_main_window_end(test_case) #print '12 = ',hwnd if hwnd>0: break except Exception,e: cnt = cnt + 1 time.sleep(1) pass win32api.keybd_event(116,0,0,0) win32api.Sleep(2) win32api.keybd_event(116,0,win32con.KEYEVENTF_KEYUP,0) time.sleep(2) win32api.keybd_event(13,0,0,0) win32api.Sleep(2) win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0) cnt = 0 result = False while cnt<60: try: hwnd = 0 hwnd = test_win.find_main_window_end('HP Run Results Viewer') if hwnd>0: result = True break except Exception,e: print e cnt = cnt + 1 time.sleep(1) pass return result
def test_case(self,test_case = r"E:\UFTTestCase\EMS_Test\EMS_FUN_000012\DemoTest\DemoTest"): time.sleep(5) WINDOW_TITLE = r"HP Unified Functional Testing" app=application.Application().connect_(title_re="HP Unified Functional Testing" ) er = win_gui() er.shortcut_keys(['Ctrl','O']) time.sleep(2) try: shell = win32com.client.Dispatch("WScript.Shell") shell.SendKeys(test_case) except Exception,e: print e time.sleep(2) app[u'Open Test'][u'Open'].Click() win32api.keybd_event(13,0,0,0) win32api.Sleep(2) win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0) test_win = win_gui() cnt = 0 while cnt<60: try: hwnd = 0 hwnd = test_win.find_main_window_end(test_case) if hwnd>0: break except Exception,e: cnt = cnt + 1 time.sleep(1) pass win32api.keybd_event(116,0,0,0) win32api.Sleep(2) win32api.keybd_event(116,0,win32con.KEYEVENTF_KEYUP,0) time.sleep(2) win32api.keybd_event(13,0,0,0) win32api.Sleep(2) win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0) cnt = 0 test_win1 = win_gui() while cnt<60: try: hwnd = None hwnd = test_win1.find_main_window_end('HP Run Results Viewer') if hwnd>0: break except Exception,e: cnt = cnt + 1 time.sleep(1) pass time.sleep(2)
def choose_conf_file(self): #get control of waveApps window. hwnd3 = win32gui.FindWindow(WAVEApps_CLASS,None) print 'hwnd3',hwnd3 time.sleep(0.5) #set waveApps window to top. win32gui.SetForegroundWindow(hwnd3) time.sleep(0.5) #move waveApps window to top left corner. win32gui.MoveWindow(hwnd3,0,0,1448,878,1) #send Alt+F to open 'File' in menu bar. win32api.Sleep(1000) win32api.keybd_event(18,0,0,0); #18Alt? win32api.keybd_event(70,0,0,0); #70F? win32api.Sleep(1000) win32api.keybd_event(70,0,win32con.KEYEVENTF_KEYUP,0); win32api.keybd_event(18,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(1000) #send O to open 'open' window. win32api.keybd_event(79,0,0,0); #79O? win32api.Sleep(1000) win32api.keybd_event(79,0,win32con.KEYEVENTF_KEYUP,0); win32api.Sleep(1000) #choose config file and open it. self.myobj.Find_Gui_edit(str_app = 'Open',control_class = 'ComboBox',filename = self.conf_file_dir,control_name = '',stop_flag = '0') self.myobj.Find_Gui_button(str_app = 'Open',control_class = 'Button',control_name = '(&O)') time.sleep(0.5) hwnd4 = win32gui.FindWindow('#32770','Open') print 'hwnd4: ',hwnd4 if hwnd4 > 0: log_public(ERR_NO_0006) self.m_ERROR_MSG = ERR_NO_0006 self.myobj.Find_Gui_button(str_app = 'Open',control_class = 'Button',control_name = '?') time.sleep(0.5) self.myobj.Find_Gui_button(str_app = 'Open',control_class = 'Button',control_name = '?') time.sleep(0.5) self.close_waveApps() print 'close_waveApps' return False else: print 'conf_file is correct.' return True #----------------------------------------------------------------------------- # Name: Mouse_LB_click # purpose: click the mouse's left butten. # explain: # Author: yuanwen # # Created: 2013/07/5 #-----------------------------------------------------------------------------