def download_file(url, dest=None, force=False): """ Download and save a file specified by url to dest directory, with force will operate silently and overwrite any existing file. """ url, filename = get_save_path(url, dest, force) if url is None: return 'Aborted!' if url: try: url_res = urllib2.urlopen(url) keep_going = True except (HTTPError, URLError) as err: msg = '\n'.join([ "\n\nERROR in Web Access! - you may be behind a firewall", "You may be able to bybass this by using a browser to download:", "\n\t%s\n\nand copying to:\n\n\t%s" % (url, filename), ]) print(msg, '\n') wx.MessageBox(msg, caption='WDOWNLOAD ERROR!', style=wx.OK|wx.CENTRE|wx.ICON_ERROR) return "Error: %s" % err with open(filename, 'wb') as outfile: block_sz = 8192 meta = url_res.info() meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all meta_length = meta_func("Content-Length") file_size = None if meta_length: file_size = int(meta_length[0]) message = "Downloading: {0}\nBytes: {1}\n".format(url, file_size) dstyle = wx.PD_APP_MODAL | wx.PD_CAN_ABORT | wx.PD_AUTO_HIDE if file_size: progress = wx.ProgressDialog('Downloading', message, maximum=1+file_size/block_sz, style=dstyle) else: progress = wx.ProgressDialog('Downloading', message, style=dstyle) file_size_dl = 0 while keep_going: read_buffer = url_res.read(block_sz) if not read_buffer: progress.Update(file_size_dl / block_sz, "message+\nDONE!") wx.Sleep(0.2) break file_size_dl += len(read_buffer) outfile.write(read_buffer) status = "{0:16}".format(file_size_dl) if file_size: status += " [{0:6.2f}%]".format(file_size_dl * 100 / file_size) (keep_going, dummy_skip) = progress.Update(file_size_dl / block_sz, message+status) wx.Sleep(0.08) # Give the GUI some update time progress.Destroy() return filename
def pHbuttonpress(self, e): count = 2 MaxProgress = 62 status = wx.ProgressDialog("Obtaining Data", "Status", MaxProgress, style=wx.PD_ELAPSED_TIME | wx.PD_AUTO_HIDE) status.Update(count) count = count + 10 status.Update(count) wx.Sleep(1) count = count + 10 status.Update(count) wx.Sleep(1) py.xlabel('most recent samples') count = count + 10 status.Update(count) wx.Sleep(1) py.ylabel(' Readings ') count = count + 10 status.Update(count) wx.Sleep(1) py.title('PH Readings') count = count + 10 status.Update(count) #Create a array of integers based on sensor readings. Y = [] Y = Obtain_pH_Readings() py.plot(Y, 'r') count = count + 10 status.Update(count) status.Destroy() py.show()
def WriteVToKeithley(self, voltage): """Sets the Keithley to a specified voltage and returns a single reading""" try: wx.Sleep(.2) visa.instrument("GPIB::22").write("SOUR:VOLT " + str(voltage)) wx.Sleep(.2) return visa.instrument("GPIB::22").ask("READ?") except: self.errorMessage('An error talking to the keithley has occurred')
def download_urllib(url, filename): """ Try to donwload via urllib.""" print("Trying to Download via urllib from:\n ", url) keep_going = True try: url_res = urllib2.urlopen(url) except (HTTPError, URLError, ssl.CertificateError) as err: print("Error: %s" % err) return False with open(filename, 'wb') as outfile: block_sz = 8192 meta = url_res.info() meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all meta_length = meta_func("Content-Length") file_size = None if meta_length: file_size = int(meta_length[0]) message = "Downloading: {0}\nBytes: {1}\n".format(url, file_size) dstyle = wx.PD_APP_MODAL | wx.PD_CAN_ABORT | wx.PD_AUTO_HIDE if file_size: progress = wx.ProgressDialog('Downloading', message, maximum=1 + file_size / block_sz, style=dstyle) else: progress = wx.ProgressDialog('Downloading', message, style=dstyle) file_size_dl = 0 while keep_going: read_buffer = url_res.read(block_sz) if not read_buffer: progress.Update(file_size_dl / block_sz, "message+\nDONE!") wx.Sleep(0.2) break file_size_dl += len(read_buffer) outfile.write(read_buffer) status = "{0:16}".format(file_size_dl) if file_size: status += " [{0:6.2f}%]".format(file_size_dl * 100 / file_size) (keep_going, dummy_skip) = progress.Update(file_size_dl / block_sz, message + status) wx.Sleep(0.08) # Give the GUI some update time progress.Destroy() result = os.path.exists(filename) and os.stat(filename).st_size > 0 return result
def Tempbuttonpress(self, e): count = 2 MaxProgress = 42 status = wx.ProgressDialog("Obtaining Data", "Status", MaxProgress, style=wx.PD_ELAPSED_TIME | wx.PD_AUTO_HIDE) status.Update(count) count = count + 5 status.Update(count) wx.Sleep(1) #Create a array of integers based on sensor readings. Y = [] Y = Obtain_temp_Readings() count = count + 20 status.Update(count) py.xlabel('sample number') py.ylabel('Readings') count = count + 10 status.Update(count) py.title('Temperature Readings') py.plot(Y, 'r') count = count + 5 status.Update(count) status.Destroy() py.show()
def onEmailIconClickPaint(self, event): dc = wx.PaintDC(self.panelmain) dc.SetBrush(wx.Brush('Red')) dc.DrawRectangle(self.emailFramePos[0], self.emailFramePos[1], 200, 800) wx.Sleep(3) event.Skip()
def process_bar(progressMax): dialog = wx.ProgressDialog(u"进度条", u"当前进度", progressMax, style=wx.PD_CAN_ABORT) keepGoing = True count = 0 while keepGoing and count < progressMax: count = count + 1 if count % (progressMax / 5) == 0: wx.Sleep(progressMax / 10000) keepGoing = dialog.Update(count) ''' if count == progressMax/5: #这里的休眠时间用实际操作的时间替代 wx.Sleep(progressMax/10000) keepGoing = dialog.Update(count) if count == progressMax/5*2 : wx.Sleep(progressMax/10000) keepGoing = dialog.Update(count) if count == progressMax/5*3: wx.Sleep(progressMax/10000) keepGoing = dialog.Update(count) if count == progressMax/5*4: wx.Sleep(progressMax/10000) keepGoing = dialog.Update(count) if count == progressMax/5*5 : wx.Sleep(progressMax/10000) keepGoing = dialog.Update(count) ''' print(count) dialog.Destroy()
def Copy_to_Clipboard_mod(self, event=None, bmp=None, pgbar=False): ''' It does the same thing as Copy_to_Clipboard. It shows progress bar for user feed back But, this add progress bar and option to paste arbitray bitmap object ''' #### some routine to change self.bitmap #### should come here... bmp_obj = wx.BitmapDataObject() if bmp is None: bmp_obj.SetBitmap(self.bitmap) else: bmp_obj.SetBitmap(bmp) if pgbar: dialog = wx.ProgressDialog ( 'Progress...', 'Coping bitmap image to System Clipboard.', maximum = 10, parent = self.GetTopLevelParent() ) for x in xrange (10): wx.Sleep (0.05) dialog.Update (x+1, 'Coping bitmap image to System Clipboard.('+str(x)+'/10') dialog.Destroy() wx.TheClipboard.Open() wx.TheClipboard.SetData(bmp_obj) wx.TheClipboard.Close() wx.TheClipboard.Flush()
def Onclicked1(self, event): if self.Text1.GetValue() == '' or self.Text2.GetValue( ) == '' or self.Text3.GetValue() == '': wx.MessageBox("参数值不能为空", "警告", wx.OK | wx.ICON_INFORMATION) else: #跳转事件 self.nb.SetSelection(1) #进度条 progressMax = 2 dialog = wx.ProgressDialog("正在运行", "Time remaining", progressMax, style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME) keepGoing = True count = 0 while keepGoing and count < progressMax: count = count + 1 wx.Sleep(1) keepGoing = dialog.Update(count) # 传参 a = int(self.Text1.GetValue()) b = float(self.Text2.GetValue()) c = int(self.Text3.GetValue()) d = int(self.Text4.GetValue()) self.SSE, self.SSR, self.RR, self.RMSE, self.ch0, self.xish = DBN_PLS_Model.canshu( a, b, c, d) dialog.Destroy()
def showProgress(): progressMax = 100 dialog = wx.ProgressDialog("Please wait : ", "Time Load remaining", progressMax, style=wx.PD_APP_MODAL | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_AUTO_HIDE) # wx.PD_CAN_ABORT | # dialog.SetFocus() keepGoing = True count = 0 ss = 1 while keepGoing and count < progressMax: pr = ScannerObj.currentProgress if pr < 50: count = pr + ss else: count = pr # print("count", ScannerObj.currentProgress) if (count >= 100): count = 100 wx.Sleep(1) keepGoing = dialog.Update(count) ss += 1 print("Loaded ...", keepGoing) dialog.Close() dialog.Destroy() print("destroyed !!")
def init_and_show_system_info(self, server_connection): self.server = server_connection init_pro_dlg = wx.ProgressDialog('正在...', '开门', 100) wx.Sleep(1) init_pro_dlg.Update(10, '放置家具') self.hard_disk_used_info = self.server.get_hard_disk_used() # initial threading, refresh system time per 1 second. init_pro_dlg.Update(30, '安排time跟班') self.time_shower = GetServerTimeThreading(self.server_ip, self.server_user, self.server_password, self.server_port) Publisher().subscribe(self.__show_time, "update_time") # initial threading, refresh system cpu per 2 second. init_pro_dlg.Update(40, '安排cpu跟班') self.memory_cpu_shower = GetServerMemoryCPUThreading( self.server_ip, self.server_user, self.server_password, self.server_port) Publisher().subscribe(self.__show_cpu, "update_cpu") init_pro_dlg.Update(50, '安排memory跟班') Publisher().subscribe(self.__show_memory, "update_memory") init_pro_dlg.Update(80, '打扫中...') self.__show_hard_disk_info() init_pro_dlg.Update(100, '主人请进') init_pro_dlg.Destroy()
def OnClose(self, event): if event.CanVeto(): if self.runthread and self.runthread.is_alive(): self.runningtask.die = True wx.Sleep(1) self.timer.Stop() event.Skip()
def __run_button_click(self,event): self.__save_button_click(event); self.crawler.set_stock_id_item( self.__item_list_name, self.__stock_id_name ); fd = wx.DirDialog(self,"Specify Output Path",style=wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON); fd_res = fd.ShowModal(); if fd_res == wx.ID_OK: output_dir = fd.GetPath(); self.crawler.output_dir = output_dir; fd.Destroy(); elif fd_res == wx.ID_CANCEL: fd.Destroy(); return; progress_max = self.crawler.tot_fetch_num; pd = wx.ProgressDialog("Fetching Progress", "Time Elapsed/Remaining", progress_max,\ style= wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME); try: self.backend = backend_thread(self.crawler); self.backend.setDaemon(True); self.backend.start(); while self.crawler.tot_fetch_count < progress_max: wx.Sleep(0.5); pd.Update(self.crawler.tot_fetch_count); # finally: pd.Destroy();
def OnTouch(self, event): #提取地区 #提取道路 test(self.userText.GetValue(), self.passText.GetValue()) ''' 可以在这里调用绘图程序 下面这一段是一个弹出progress_bar的代码 这段代码可以进行修改让它同步绘图过程 ''' progressMax = 100 dialog = wx.ProgressDialog("A progress box", "Time remaining", progressMax, style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME) keepGoing = True count = 0 while keepGoing and count < progressMax: count = count + 1 wx.Sleep(1) keepGoing = dialog.Update(count) #更新进度条进度 dialog.Destroy() self.sizer.Layout() #关键所在,强制sizer重新计算并布局sizer中的控件
def run(self): while not self.cancel: if self.refresh > 0: self.lock.acquire() self.refreshVM() self.lock.release() self.refresh = self.refresh - 1 else: if self.tenRefresh == 0: # Del by wangderan 20150525 start #Session.logout() # Del by wangderan 20150525 end url = 'http://%s%s' % (Setting.getServer(), ":5000/v2.0") _auth_url = url username = Setting.getLastLogin() _user = username _password = LoginFrame.PassWord() ret, reason, detail = Session.login( _auth_url, _user, _password) Logger.info("ReLogin Status: Result: %s", ret) self.lock.acquire() self.refreshVM() self.lock.release() self.tenRefresh = 900 else: self.tenRefresh = self.tenRefresh - 1 wx.Sleep(2)
def SendMail(self, rptname, rpttitle=''): r = None d2p = dbm.DocMag() d2p._info.anag = None wait = None totemails = 0 c = self.dbdocs._GetFieldIndex('dastampare', inline=True) rs = self.dbdocs.GetRecordset() for n in range(self.dbdocs.RowsCount()): if rs[n][c]: totemails += 1 try: try: for n, doc in enumerate(self.dbdocs): if doc.dastampare: d2p.Get(doc.id) pathname = d2p.GetPrintPathName() filename = d2p.GetPrintFileName() if r is None: #d2p._info.titleprint = rpttitle r = rpt.Report(self, d2p, rptname, rowFunc=self.SetAnagAndRegCon, output="STORE", changepathname=pathname, changefilename=filename, forcechoice=True, emailbutton=totemails) ur = r.GetUsedReport() if ur is None: break sendfile = r.GetUsedReport().GetFileName() else: ur = r.StartReport(filename) sei = d2p.SendMail_Prepare() if sei.errors: aw.awu.MsgDialog(self, sei.request, style=wx.ICON_ERROR) else: if wait is None: wait = aw.awu.WaitDialog(self, message="Invio email in corso...", maximum=self.dbdocs.RowsCount()) wx.Sleep(3) wait.SetMessage("Invio a: %s" % sei.sendto) wx.Sleep(3) d2p.SendMail(sei, ur.GetFileName()) if wait is not None: wait.SetValue(n) except Exception, e: aw.awu.MsgDialog(self, repr(e.args)) finally: if wait is not None: wait.Destroy()
def _HandleEncodingError(self, control): """Handle trying to reload the file the file with a different encoding Until it succeeds or gives up. @param control: stc @return: bool """ # Loop while the load fails prompting to try a new encoding tried = None fname = control.GetFileName().strip(os.sep) fname = fname.split(os.sep)[-1] while True: doc = control.GetDocument() doc.ClearLastError() if tried is None: enc = doc.GetEncoding() if enc is None: enc = ed_txt.DEFAULT_ENCODING else: enc = tried msg = _("The correct encoding of '%s' could not be determined.\n\n" "Choose an encoding and select Ok to open the file with the chosen encoding.\n" "Click Cancel to abort opening the file") % fname # On some systems it seems that default encoding ends up being # None so default to utf-8 for choices. if enc is None: enc = 'utf_8' dlg = eclib.EncodingDialog(self, msg=msg, title=_("Choose an Encoding"), default=enc) bmp = wx.ArtProvider.GetBitmap(str(ed_glob.ID_DOCPROP), wx.ART_OTHER) if bmp.IsOk(): dlg.SetBitmap(bmp) dlg.CenterOnParent() result = dlg.ShowModal() if dlg: enc = dlg.GetEncoding() dlg.Destroy() else: result = wx.ID_CANCEL # Don't want to open it in another encoding if result == wx.ID_CANCEL: return False else: control.SetEncoding(enc) tried = enc ok = control.LoadFile(control.GetFileName()) if ok: return True else: # Artificially add a short pause, because if its not there # the dialog will be shown again so fast it wont seem # like reloading the file was even tried. wx.Sleep(1)
def getCharForTeam(self, team_index): team_name_input, team_char_id, team_char = self.teams[team_index] busy = wx.BusyInfo( f'{strings.PRESS_KEY_MESSAGE} {team_name_input.GetValue()}\n{strings.PRESS_KEY_INFO}', self) wx.Sleep(2) self.waitingTeamForKey = team_index self.add_button.SetFocus()
def on_change_spec_wl(self, evt): self.spec_wl = float(self.frame.m_textCtrl_set_spec_wl.GetValue()) self.frame.m_statusBar.SetStatusText( "Setting spectrometer wavelength to %f nm ..." % self.spec_wl) self.spec.write_wl_nonblock(self.spec_wl) wx.Yield() wx.Sleep(1) self.spec_done = False while not self.spec_done: self.spec_done = self.spec.read_done_status() self.spec_wl_current = self.spec.read_wl() self.frame.m_textCtrl_current_spec_wl.SetValue( "%f" % self.spec_wl_current) wx.Yield() wx.Sleep(1) self.frame.m_textCtrl_set_spec_wl.SetValue("") self.frame.m_statusBar.SetStatusText("Done setting Spectrometer")
def OnClickGetAll(self, event): event.Skip() gd.cmd_write = "\x3F\x10" while gd.cmd_write is not None: wx.Sleep(0.01) dlg = ParaPanel(None) dlg.ShowModal() pass
def AppStarted(self): if self.TestDBVers(): import xframe as xfr frame = xfr.XFrame(None, -1, "X4GA") frame.Show(True) frame.Update() while not wx.SafeYield(onlyIfNeeded=True): wx.Sleep(.1) self.SetTopWindow(frame)
def run(self): self.syncTries = 0 while gd.isReadExit == False: #When the gd.gSerialDev is None; Try open one port if gd.gSerialDev is None: self.findAndOpenPort() wx.Sleep(1) else: if self.sync == 0: # Not synchronized yet buf = gd.gSerialDev.read(1) if len(buf) == 0: # Read Timeout; try sync another time self.syncTries = self.syncTries + 1 print "Try times=" + str(self.syncTries) else: #reset timeout to 2 sec gd.gSerialDev.timeout = 2 if ord(self.sync_last_byte) == 0x85 and ord( buf[0]) == 0x75: #print "data synchronized" self.sync = 1 buf = gd.gSerialDev.read(19) self.process_data(buf, 0) continue else: self.sync_last_byte = buf[0] self.syncTries = self.syncTries + 1 else: # Data synchronized buf = gd.gSerialDev.read(21) if len(buf) == 0: gd.gSerialDev.close() gd.gSerialDev = None self.sync = 0 self.sync_last_byte = chr(0) else: if ord(buf[0]) != 0x85 or ord(buf[1]) != 0x75: #print "data format error, lost sync" self.sync = 0 self.sync_last_byte = chr(0) continue self.process_data(buf, 2) if self.syncTries > 21: self.syncTries = 0 print "Try timeout, try next comm port\n" gd.gSerialDev.close() gd.gSerialDev = None #print "ExitRead" if gd.gSerialDev is not None: gd.gSerialDev.close() gd.gSerialDev = None if self.commPort is not None: self.commPort.close()
def run(self): while not self.cancel: p = self.window.GetProgress() + 20 wx.CallAfter(self.window.Update, p) if p >= 100: wx.CallAfter(self.window.TimedOut) break wx.Sleep(1)
def test5(frm): message = """A long message with line breaks: Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.""" with BusyInfo(message, frm): wx.Sleep(2)
def onbutton_start_service(self,event): sqlconns.sql_command("UPDATE d_inbio_misc SET value = 0 WHERE property like 'paused'") progressMax = 7 dialog = wx.ProgressDialog("Progress Information", ("Starting Inbio Comunications Service."), progressMax) keepGoing = True count = 0 while keepGoing and count < progressMax: count = count + 1 wx.Sleep(1) keepGoing = dialog.Update(count) dialog.Destroy() self.button_start_service.Enable(False) self.button_stop_service.Enable(True)
def OnClickGet(self, event): #write something to obtain the parameter print "Get parameter " gd.cmd_write = "\x3F\x02\x33" wx.Sleep(1) readIndex = 0 while (readIndex < self.totalReg): wx.Sleep(0.002) gd.sensor_data_lock.acquire() if gd.parameterData is not []: buf = gd.parameterData gd.parameterData = [] gd.sensor_data_lock.release() if buf is not []: for i in range(0, len(buf), 2): strValue = hex(buf[i + 1]).lstrip('0x') strValue = strValue.rjust(2, '0') self.paraEdit[buf[i]].SetValue(strValue) readIndex = readIndex + 1 print readIndex pass
def ProgressDialogTest(): maxSize = 100 dlg = ProgressDialog(None, icons.getSplashBitmap(), 100, "VERSION") dlg.Show() count = 0 while count < maxSize: count = count + 1 wx.Sleep(0.2) dlg.UpdateGauge('update ' + str(count), count) dlg.Destroy()
def button_click(self, event): """button has been clicked, do something""" wisdom_list = [ "Man who run in front of car, get tired.", "Man who run behind car, get exhausted.", "Man who drive like hell, bound to get there.", "Man who scratches butt should not bite fingernails.", "Man who fight wife all day, get no piece at night.", "Man who sit on tack, get point." ] self.button.SetLabel(random.choice(wisdom_list)) # wait 2.5 seconds wx.Sleep(2.5) self.button.SetLabel("Click the button")
def run(self): while gd.isWriteExit == False: if gd.cmd_write != None and gd.gSerialDev != None: print "write something" gd.gSerialDev.write(gd.cmd_write) gd.cmd_write = None else: wx.Sleep(0.002) #print "Exit write" if gd.gSerialDev != None: gd.gSerialDev.close() gd.gSerialDev = None
def progress(self): progressMax = 8 dialog = wx.ProgressDialog("Progress", "Time remaining", progressMax, style=wx.PD_AUTO_HIDE | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_SMOOTH) keepGoing = True count = 0 while keepGoing and count < progressMax: count = count + 1 wx.Sleep(1) keepGoing = dialog.Update(count) dialog.Destroy()