1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| from concurrent.futures import ThreadPoolExecutor as Pool
import subprocess
from PyQt5.QtCore import QThread, pyqtSignal
class Launcher(QThread):
on_update = pyqtSignal(float)
on_done = pyqtSignal()
_abort = False
_dialog = None
def __init__(self, count=10, display_dialog=True):
super().__init__()
self.count = count
if display_dialog:
dialog = self._dialog = QProgressDialog("En cours...", "Annuler", 0, 100)
self.on_update.connect(dialog.setValue)
self.on_done.connect(dialog.reset)
dialog.show()
self.on_done.connect(self.shutdown)
def run_item(self, ident):
if not self._abort:
subprocess.call ('python -c "import time; time.sleep(0.5)"')
return ident
def run(self):
step = 100 / self.count
done = 0
def callback(future):
nonlocal done
if not self._abort:
done += step
print('callback', done, 'ix', future.result())
self.on_update.emit(done)
if done >= 100 :
self.on_done.emit()
self.futures = {}
pool = self.pool = Pool(max_workers=2)
for z in range(self.count):
future = pool.submit(self.run_item, z)
future.add_done_callback(callback)
self.futures[z] = future
def shutdown(self): # ** too much **
self._abort = True
# for f in self.futures.values():
# f.cancel()
self.pool.shutdown(wait=True)
self.exit()
if __name__ == '__main__':
from PyQt5.QtWidgets import QApplication, QProgressDialog, QPushButton
def do_launch():
launcher = Launcher(display_dialog=False)
# dialog = QProgressDialog("En cours...", "Annuler", 0, 100)
# launcher.on_update.connect(dialog.setValue)
# launcher.on_done.connect(dialog.reset)
launcher.start()
launcher.exec_()
# launcher.shutdown()
app = QApplication([])
btn = QPushButton('start')
btn.clicked.connect(do_launch)
btn.show()
exit(app.exec_()) |
Partager