Skip to content

Instantly share code, notes, and snippets.

@hannesdelbeke
Created October 22, 2023 22:37
Show Gist options
  • Save hannesdelbeke/036654b496b7f637163b80e8b6149682 to your computer and use it in GitHub Desktop.
Save hannesdelbeke/036654b496b7f637163b80e8b6149682 to your computer and use it in GitHub Desktop.
get console output in a qt widget, tested in Blender.
import sys
import subprocess
from PySide2.QtWidgets import QLineEdit, QApplication, QMainWindow, QTextEdit, QVBoxLayout, QPushButton, QWidget
from PySide2.QtCore import QTimer
from PySide2.QtGui import QColor, QTextCursor
class RealTimeOutputApp(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Real-Time Output Example")
self.central_widget = QWidget()
self.setCentralWidget(self.central_widget)
layout = QVBoxLayout(self.central_widget)
self.command_line = QLineEdit()
layout.addWidget(self.command_line)
self.text_edit = QTextEdit()
layout.addWidget(self.text_edit)
self.start_button = QPushButton("List Files in Directory")
layout.addWidget(self.start_button)
self.start_button.clicked.connect(self.start_command)
self.process = None
self.timer = QTimer(self)
self.timer.timeout.connect(self.read_output)
self.read_timer_started = False
def start_command(self):
try:
self.text_edit.clear()
command = self.command_line.text() # Get the command from the QLineEdit
#command = ["cmd", "/c", "tree"] # Sample command to list files in a directory
self.process = subprocess.Popen(command,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
universal_newlines=True, errors='ignore')
# Start a timer to periodically check for new output
if not self.read_timer_started:
self.timer.start(1) # Adjust the interval as needed (every x milisec)
self.read_timer_started = True
except Exception as e:
self.add_error(str(e))
def read_output(self):
if not self.process:
self.add_error("No process avaiable")
return
stdout_line = self.process.stdout.read() # Adjust the buffer size as needed
stderr_line = self.process.stderr.read()
if stdout_line:
self.text_edit.moveCursor(QTextCursor.End)
self.text_edit.insertPlainText(stdout_line)
#self.repaint()
if stderr_line:
# Print error output in red
self.add_error(stderr_line)
if not stdout_line and not stderr_line and self.process.poll() != None:
# The process has finished
self.process = None
self.read_timer_started = False
self.timer.stop()
def add_error(self, lines):
color = "red"
if lines.lower().startswith("warning"):
color = "yellow"
self.text_edit.setTextColor(QColor(color))
self.text_edit.insertPlainText(lines)
self.text_edit.setTextColor(QColor("black"))
main_window = RealTimeOutputApp()
main_window.show()
@hannesdelbeke
Copy link
Author

image image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment