问题
I create a button and try to run multiprocessing when I click button ,
but the UI is become blocked . I hope process run in backgorund .
How can I fix it ?
from PySide2 import QtCore,QtGui,QtWidgets
import sys
import multiprocessing
from threading import Timer
class TTT(multiprocessing.Process):
def __init__(self):
super(TTT, self).__init__()
self.daemon = True
def run(self):
while True:
t = Timer(5, self.doSomething)
t.start()
t.join()
def doSomething(self):
try:
print('123')
except Exception as e:
print(e)
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
btn = QtWidgets.QPushButton('run process')
btn.clicked.connect(self.create_process)
self.setCentralWidget(btn)
def create_process(self):
QtWidgets.QMessageBox.information(self,'hhh','hhh')
t = TTT()
t.start()
t.join()
if __name__=="__main__":
app=QtWidgets.QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
回答1:
I have never used multiprocessing, but docs says that the join() method blocks the caller until it is finished. Putting the method in an infinite loop will block the caller(the UI) forever.
回答2:
Bendegúz Szatmári already answer the main question.
I just want to let you know that use Process is not best idea in most of usage. Different process does not share memory with your program. You can not control them so easily as different thread.
Here is simple example how you can Start end Stop different thread.
from PyQt5 import QtWidgets
from PyQt5.QtCore import *
import sys
import time
class TTT(QThread):
def __init__(self):
super(TTT, self).__init__()
self.quit_flag = False
def run(self):
while True:
if not self.quit_flag:
self.doSomething()
time.sleep(1)
else:
break
self.quit()
self.wait()
def doSomething(self):
print('123')
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.btn = QtWidgets.QPushButton('run process')
self.btn.clicked.connect(self.create_process)
self.setCentralWidget(self.btn)
def create_process(self):
if self.btn.text() == "run process":
print("Started")
self.btn.setText("stop process")
self.t = TTT()
self.t.start()
else:
self.t.quit_flag = True
print("Stop sent")
self.t.wait()
print("Stopped")
self.btn.setText("run process")
if __name__=="__main__":
app=QtWidgets.QApplication(sys.argv)
ex = MainWindow()
ex.show()
sys.exit(app.exec_())
回答3:
Here's a nice strategy:
https://elsampsa.github.io/valkka-examples/_build/html/qt_notes.html#python-multiprocessing
Features:
- You can send Qt signals from the multiprocess
- You can send Qt signals into the multiprocess
来源:https://stackoverflow.com/questions/47649159/how-do-i-properly-perform-multiprocessing-from-pyqt