I have a file script.py which executes some operations and uses some "print" statements to communicate with the user.
Using PyQt5, I created a separate file gui.py where I created a GUI with some widgets, including a "run" button and a QTextEdit. When I press that button, I want "script.py" to be executed and every line of its output to be redirected on my QTextEdit in real time
I managed to execute the script and view it's output... but,while it works perfectly on console, the QTextEdit is updated only when script.py has concluded its execution.
This is my code :
class gui(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
def run():
try:
p = subprocess.Popen("python script.py", stdout=subprocess.PIPE)
for line in iter(p.stdout.readline, b''):
if line != "b''":
line = str(line)[2:-5] # eliminates b' and \r\n'
print(line) # This works real-time
output.append(line) # this does not
p.stdout.close()
p.wait()
except Exception as e:
print(str(e))
button_run = QPushButton("&Run", self)
button_run.clicked.connect(run)
output = QTextEdit()
output.setPlaceholderText("Text will appear here")
output.setReadOnly(True)
"""
rest of initUI....
"""
if __name__ == '__main__':
app = QApplication(sys.argv)
ui = gui()
sys.exit(app.exec_())
I tried to use QProcess, but I can't wrap my head around it.
You should use a worker thread and communicate your main app with your worker by Qt slots and signals. See this example it's coded in c++, but is usefull to get the idea.
使用Qt的QProcess而不是在线程中使用subprocess
进程会更加容易-它具有readyRead
信号和readLine
方法之类的东西。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.