def run(is_alive): is_alive.set() while is_alive.is_set(): text = 'Main Count: {}'.format(data['counter']) get_updater().call_in_main(text_edit.append, text) data['counter'] += 1 time.sleep(0.01) # Some delay/waiting is required
def run_continuous_update(): """Run the continuous update example.""" import time import threading from qtpy import QtWidgets from qt_thread_updater import get_updater app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) lbl = QtWidgets.QLabel("Continuous Count: 0") lbl.resize(300, 300) lbl.show() data = {'counter': 0} def update(): """Update the label with the current value.""" lbl.setText('Continuous Count: {}'.format(data['counter'])) get_updater().register_continuous(update) def run(is_alive): is_alive.set() while is_alive.is_set(): data['counter'] += 1 # time.sleep(0.001) # Not needed (still good to have some delay to release the thread) alive = threading.Event() th = threading.Thread(target=run, args=(alive, )) th.start() get_updater().delay(5, app.quit) # Quit after 5 seconds app.exec_() alive.clear() cleanup_app()
def run_call_in_main(): """Run the updater call_in_main. This will be inefficient and may need to run slower (time.sleep).""" import time import threading from qtpy import QtWidgets from qt_thread_updater import get_updater app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) text_edit = QtWidgets.QTextEdit() text_edit.resize(300, 300) text_edit.setReadOnly(True) text_edit.show() data = {'counter': 0} def run(is_alive): is_alive.set() while is_alive.is_set(): text = 'Main Count: {}'.format(data['counter']) get_updater().call_in_main(text_edit.append, text) data['counter'] += 1 time.sleep(0.01) # Some delay/waiting is required alive = threading.Event() th = threading.Thread(target=run, args=(alive, )) th.start() # Quit after 2 seconds (So many events from call in main 2 waits longer than 2 seconds) get_updater().delay(2, app.quit) app.exec_() alive.clear() cleanup_app()
def write(self, text, *args, **kwargs): """Put data on the queue to add to the TextEdit view.""" text = str(text) if len(text) > 0: with self._queue_lock: self._queue += text get_updater().call_latest(self.update_display)
def run_simple_thread_example(): """Run the normal usage thread example.""" import time import threading from qtpy import QtWidgets from qt_thread_updater import get_updater app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) lbl = QtWidgets.QLabel("Latest Count: 0") lbl.resize(300, 300) lbl.show() data = {'counter': 0} def run(is_alive): is_alive.set() while is_alive.is_set(): text = 'Latest Count: {}'.format(data['counter']) get_updater().call_latest(lbl.setText, text) data['counter'] += 1 time.sleep( 0.001 ) # Not needed (still good to have some delay to release the thread) alive = threading.Event() th = threading.Thread(target=run, args=(alive, )) th.start() get_updater().delay(5, app.quit) # Quit after 5 seconds app.exec_() alive.clear() cleanup_app()
def run(is_alive): is_alive.set() while is_alive.is_set(): text = 'Latest Count: {}'.format(data['counter']) get_updater().call_latest(lbl.setText, text) data['counter'] += 1 time.sleep( 0.001 ) # Not needed (still good to have some delay to release the thread)
def download_win(self, url: str) -> None: try: self.dialogSignal.emit('Downloading the update. Please wait...') filedata = urlopen(url) datatowrite = filedata.read() filename = "" with open(os.path.join(os.path.join(tempDir.name, ".."), "SomePythonThings-Zip Manager-Updater.exe"), 'wb') as f: f.write(datatowrite) filename = f.name self.dialogSignal.emit('Launching the updater. Please wait') log(f"[ OK ] file downloaded to {filename}".format(filename)) get_updater().call_in_main(self.launch_win, filename) except Exception as e: if debugging: raise e self.throwErrorSignal.emit("SomePythonThings Zip Manager", "An error occurred while downloading the SomePythonTings Zip Manager installer. Please check your internet connection and try again later\n\nError Details:\n{0}".format(str(e))) self.closeDialogSignal.emit()
def write(self, text, color=None, fmt=None, *args, **kwargs): """Put data on the queue to add to the TextEdit view. Args: text (str): String text to write. color (str/QColor)[None]: String color name to write the text foreground with. If this argument is None the currentCharFormat() or given fmt will be used. fmt (QTextCharFormat)[None]: Use this text format to write the text. """ text = str(text) if len(text) > 0: # Get and copy the format. Do not permanently change the format if fmt is None: fmt = self._orig_fmt or self.currentCharFormat() fmt = QtGui.QTextCharFormat(fmt) # Change the color if color is not None: fmt.setForeground(QtGui.QBrush(QtGui.QColor(color))) with self._queue_lock: self._queue.append((text, fmt)) get_updater().call_latest(self.update_display)
def run_delay(): """Run the updater to call a function delayed.""" import time import threading from qtpy import QtWidgets from qt_thread_updater import get_updater app = QtWidgets.QApplication.instance() or QtWidgets.QApplication([]) text_edit = QtWidgets.QTextEdit() text_edit.resize(300, 300) text_edit.setReadOnly(True) text_edit.show() now = time.time() def update_text(set_time): text_edit.append('Requested {:.04f} Updated {:.04f}'.format( set_time, time.time() - now)) # Lower the timeout so it runs at a faster rate. get_updater().timeout = 0 # 0.0001 # Qt runs in milliseconds get_updater().delay(0.5, update_text, 0.5) get_updater().delay(1, update_text, 1) get_updater().delay(1.5, update_text, 1.5) get_updater().delay(2, update_text, 2) get_updater().delay(2.5, update_text, 2.5) get_updater().delay(3, update_text, 3) get_updater().delay(5, app.quit) # Quit after 5 seconds app.exec_() cleanup_app()
def run(self): log("[ ] Starting compression thread...") try: zipObj = zipfile.ZipFile(self.zipfilename, 'w') totalFiles = 0 for item in self.files: self.changeItemIcon.emit(item, 2, "not.ico") self.changeItemText.emit(item, 2, "Queued") totalFiles += 1 log('[ INFO ] Total number of files: ' + str(totalFiles)) actualFile = 0 try: algorithm = self.parent.algorithm.getSelectedItem() if (algorithm == "None"): log("[ OK ] Selected compression algorithm is none: {0}" .format(algorithm)) compression_type = zipfile.ZIP_STORED elif (algorithm == "LZMA"): log("[ OK ] Selected compression algorithm is lzma: {0}" .format(algorithm)) compression_type = zipfile.ZIP_LZMA elif (algorithm == "BZIP2"): log("[ OK ] Selected compression algorithm is bzip2: {0}" .format(algorithm)) compression_type = zipfile.ZIP_BZIP2 else: log("[ OK ] Selected compression algorithm is deflated: {0}" .format(algorithm)) compression_type = zipfile.ZIP_DEFLATED self.updateProgressBar[int, int].emit(0, totalFiles) except Exception as e: if (debugging): raise e self.throwWarning.emit( "SomePythonThongs Zip Manager", "An error occurred while selecting your desired compression algorithm. Compression algorithm will be \"Deflated\". " ) compression_type = zipfile.ZIP_DEFLATED try: self.parent.compression_level = self.parent.rate.getSelectedItem( ) except Exception as e: if (debugging): raise e log(f"[ OK ] Compress rate set to {self.parent.compression_level}" ) errors = "" allDone = True for item in self.files: item: QtWidgets.QTreeWidgetItem self.changeItemIcon.emit(item, 2, "loading.ico") self.changeItemText.emit(item, 2, "Compressing") subdir = item.text(4) path = (item.text(3), '/'.join(item.text(3).split('/')[:-1]), subdir) try: self.updateProgressBar[int, int, str].emit( actualFile, totalFiles, path[0]) os.chdir(path[1]) if not self.zipfilename == path[0]: t = KillableThread( target=self.pureCompress, args=(zipObj, path[0].split('/')[-1], os.path.join(subdir, path[0].split('/')[-1]), compression_type), daemon=True) t.start() while t.is_alive(): if not (self.parent.isCompressing): log("[ WARN ] User cancelled the zip creation!" ) t.shouldBeRuning = False for item in self.files: self.changeItemIcon.emit( item, 2, "warn.ico") self.changeItemText.emit( item, 2, "Canceled") self.throwWarning.emit( "SomePythonThings Zip Manager", "User cancelled the zip creation") time.sleep(0.5) zipObj.close() try: os.remove(self.zipfilename) except: log("[ WARN ] Unable to remove zip file" ) self.parent.files = [] break else: time.sleep(0.01) t.join() if (self.errorWhileCompressing != None): raise self.errorWhileCompressing log('[ OK ] File "' + str(path[0].split('/')[-1]) + f'" added successfully on relative directory {subdir}' ) else: log('[ WARN ] File "' + str(path[0].split('/')[-1]) + '" skipped because it is the output zip') self.changeItemIcon.emit(item, 2, "ok.ico") self.changeItemText.emit(item, 2, "Done") except Exception as e: allDone = False self.changeItemIcon.emit(item, 2, "warn.ico") self.changeItemText.emit(item, 2, str(e)) log(f'[ FAILED ] Unable to add file "{str(path)}": {e}' ) errors += " - " + str(path[0]) + "\n" finally: actualFile += 1 if not (self.parent.isCompressing): break zipObj.close() if (self.parent.isCompressing): get_updater().call_in_main(self.parent.stopLoading) notify( "Compression Done!", "SomePythonThings Zip Manager has finished compressing the selected files and folders.", self.parent.window) if allDone: self.throwInfo.emit( "SomepythonThings Zip Manager", 'The Zip file was created sucessfully!') log('[ OK ] zip file created sucessfully') else: self.throwWarning.emit( "SomePythonThings Zip Manager", 'The Zip file was created with some errors: \n' + str(errors)) log('[ WARN ] zip file created with errors:\n' + str(errors)) get_updater().call_in_main(openOnExplorer, self.zipfilename, force=False) except Exception as e: get_updater().call_in_main(self.parent.stopLoading) if (debugging): raise e log('[ FAILED ] Error occurred while creating zip File') try: self.throwError.emit( "SomePythonThings Zip Manager", "Unable to create zip file " + self.zipfilename + ".\n\nError reason:\n" + str(e)) except: self.throwError.emit( "SomePythonThings Zip Manager", "Unable to create zip file.\n\nError reason:\n" + str(e))
def download(): global msg try: response = urllib.request.urlopen(app_link) response = response.read().decode("utf8") version = response.split("///")[0] links = { 'debian': response.split("///")[2].replace('\n', ''), 'win32': response.split("///")[3].replace('\n', ''), 'win64': response.split("///")[4].replace('\n', ''), 'macos': response.split("///")[5].replace('\n', '') } try: os.remove("\\SomePythonThings\\somepythonthings-{0}-installer.exe". format(app_codename)) except Exception as e: print("Can't remove installer") if (os.system("cd %windir%\\..\\Program Files (x86)\\") == 0): url = (links["win64"]) print('Win64') else: url = (links['win32']) print('Win32') print('Download link is ' + url) os.chdir("\\") try: os.chdir("SomePythonThings") except FileNotFoundError: os.mkdir("SomePythonThings") os.chdir("SomePythonThings") with urllib.request.urlopen(url) as Response: Length = Response.getheader('content-length') BlockSize = 10000 if Length: Length = int(Length) BlockSize = max(65535, Length // 10000) datatowrite = Response.read(0) BufferAll = io.BytesIO() Size = 0 while True: BufferNow = Response.read(BlockSize) datatowrite += BufferNow if not BufferNow: break BufferAll.write(BufferNow) Size += len(BufferNow) if Length: percent = int((Size / Length) * 100) get_updater().call_in_main(progress.setMaximum, 100) get_updater().call_in_main(progress.setValue, percent) get_updater().call_in_main( label.setText, f"Downloading {app_name} (Version {version}) {percent}% Done" ) with open( "/SomePythonThings/somepythonthings-{0}-installer.exe". format(app_codename), 'ab') as f: f.write(datatowrite) get_updater().call_in_main(progress.setMaximum, 0) get_updater().call_in_main(progress.setValue, 0) get_updater().call_in_main( label.setText, f"Installing {app_name} (Version {version})...") subprocess.run([ "%windir%\\..\\SomePythonThings\\somepythonthings-{0}-installer.exe" .format(app_codename), "/verysilent" ], shell=True) get_updater().call_in_main(label.setText, f"{app_name} was installed successfully!") get_updater().call_in_main(msg.setIcon, QtWidgets.QMessageBox.Information) get_updater().call_in_main(msg.setWindowTitle, "Installation done!") get_updater().call_in_main( msg.setText, f"{app_name} was installed successfully to your computer!") get_updater().call_in_main(msg.exec_) get_updater().call_in_main(sys.exit) except Exception as e: get_updater().call_in_main(msg.setIcon, QtWidgets.QMessageBox.Critical) get_updater().call_in_main(msg.setWindowTitle, "An error occurred") get_updater().call_in_main( msg.setText, f"We are unable to download {app_name}. Please check your internet connection and try again later.\n\nError details: {str(e)}" ) get_updater().call_in_main(msg.exec_) get_updater().call_in_main(sys.exit)