Source

embeddedpyqt / console.py

Full commit
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QDialog, QPlainTextEdit, QVBoxLayout, QSplitter, QPushButton, QTextCursor


class EditorWidget(QPlainTextEdit):

	
	def __init__(self, parent):
		super(EditorWidget, self).__init__(parent)



class OutputWidget(QPlainTextEdit):

	
	def __init__(self, parent):
		super(OutputWidget, self).__init__(parent)
		self.setReadOnly(True)
		sys.stdout = self
		sys.stderr = self
		self.buf = u""
		self.startTimer(500)

		
	def write(self, s):
		sys.__stdout__.write(s)
		self.buf += unicode(s)

		
	def writeline(self, s):
		self.write(u"%s\n" % s)

		
	def timerEvent(self, event):
		self.flush()

		
	def flush(self):
		if self.buf:
			if not self.window().isVisible():
				self.window().show()
			self.moveCursor(QTextCursor.End, QTextCursor.MoveAnchor)
			self.textCursor().insertText(self.buf)			
			self.moveCursor(QTextCursor.End, QTextCursor.MoveAnchor)
			self.ensureCursorVisible()
			self.buf = ""


	
class Console(QDialog):


	def __init__(self, namespace=None):
		QDialog.__init__(self)
		if namespace is None:
			namespace = {}
		self.namespace = namespace
		self.vblayout = QVBoxLayout(self)
		self.splitter = QSplitter(Qt.Vertical, self)
		self.layout().addWidget(self.splitter)
		self.edit = EditorWidget(self.splitter)
		self.edit.setPlainText("print 'Hello, world'")
		self.output = OutputWidget(self.splitter)		
		self.runButton = QPushButton(self, text="&Run")
		self.runButton.clicked.connect(self.run)
		self.layout().addWidget(self.runButton)
		self.edit.setFocus()

		
	def run(self):
		code = unicode(self.edit.toPlainText())
		try:
			exec code in self.namespace
		except Exception, e:
			print e
			import traceback
			traceback.print_exc()
	
		

		

		
if __name__ == "__main__":
	import sys
	from PyQt4.QtGui import QApplication
	app = QApplication(sys.argv)
	win = Console()
	win.show()
	app.exec_()