1 # source: http://stackoverflow.com/questions/2758159/how-to-embed-a-python-interpreter-in-a-pyqt-widget
5 from PyQt4 import QtCore
6 from PyQt4 import QtGui
10 class Console(QtGui.QPlainTextEdit):
11 def __init__(self, prompt='>> ', startup_message='', parent=None):
12 QtGui.QPlainTextEdit.__init__(self, parent)
19 self.setGeometry(50, 75, 600, 400)
20 self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere)
21 self.setUndoRedoEnabled(False)
22 self.document().setDefaultFont(QtGui.QFont("monospace", 10, QtGui.QFont.Normal))
23 self.showMessage(startup_message)
25 self.updateNamespace({'run':self.run_script})
27 def run_script(self, filename):
28 with open(filename) as f:
30 result = eval(script, self.namespace, self.namespace)
34 def updateNamespace(self, namespace):
35 self.namespace.update(namespace)
37 def showMessage(self, message):
38 self.appendPlainText(message)
47 prompt = '.' * len(self.prompt)
51 self.completions_pos = self.textCursor().position()
52 self.completions_visible = False
54 self.appendPlainText(prompt)
55 self.moveCursor(QtGui.QTextCursor.End)
59 curr_line = unicode(doc.findBlockByLineNumber(doc.lineCount() - 1).text())
60 curr_line = curr_line.rstrip()
61 curr_line = curr_line[len(self.prompt):]
64 def setCommand(self, command):
65 if self.getCommand() == command:
67 self.moveCursor(QtGui.QTextCursor.End)
68 self.moveCursor(QtGui.QTextCursor.StartOfLine, QtGui.QTextCursor.KeepAnchor)
69 for i in range(len(self.prompt)):
70 self.moveCursor(QtGui.QTextCursor.Right, QtGui.QTextCursor.KeepAnchor)
71 self.textCursor().removeSelectedText()
72 self.textCursor().insertText(command)
73 self.moveCursor(QtGui.QTextCursor.End)
76 def show_completions(self, completions):
77 if self.completions_visible:
78 self.hide_completions()
81 c.setPosition(self.completions_pos)
83 completions = map(lambda x: x.split('.')[-1], completions)
84 t = '\n' + ' '.join(completions)
88 self.completions_end = c.position()
90 self.moveCursor(QtGui.QTextCursor.End)
91 self.completions_visible = True
94 def hide_completions(self):
95 if not self.completions_visible:
98 c.setPosition(self.completions_pos)
99 l = self.completions_end - self.completions_pos
100 for x in range(l): c.deleteChar()
102 self.moveCursor(QtGui.QTextCursor.End)
103 self.completions_visible = False
106 def getConstruct(self, command):
108 prev_command = self.construct[-1]
109 self.construct.append(command)
110 if not prev_command and not command:
111 ret_val = '\n'.join(self.construct)
117 if command and command[-1] == (':'):
118 self.construct.append(command)
123 def getHistory(self):
126 def setHisory(self, history):
127 self.history = history
129 def addToHistory(self, command):
130 if command and (not self.history or self.history[-1] != command):
131 self.history.append(command)
132 self.history_index = len(self.history)
134 def getPrevHistoryEntry(self):
136 self.history_index = max(0, self.history_index - 1)
137 return self.history[self.history_index]
140 def getNextHistoryEntry(self):
142 hist_len = len(self.history)
143 self.history_index = min(hist_len, self.history_index + 1)
144 if self.history_index < hist_len:
145 return self.history[self.history_index]
148 def getCursorPosition(self):
149 return self.textCursor().columnNumber() - len(self.prompt)
151 def setCursorPosition(self, position):
152 self.moveCursor(QtGui.QTextCursor.StartOfLine)
153 for i in range(len(self.prompt) + position):
154 self.moveCursor(QtGui.QTextCursor.Right)
156 def runCommand(self):
157 command = self.getCommand()
158 self.addToHistory(command)
160 command = self.getConstruct(command)
163 tmp_stdout = sys.stdout
166 def __init__(self, write_func):
167 self.write_func = write_func
173 def write(self, text):
175 stripped_text = text.rstrip('\n')
176 self.write_func(stripped_text)
177 QtCore.QCoreApplication.processEvents()
178 self.skip = not self.skip
180 if command == 'help()':
181 self.appendPlainText("no help here!")
185 sys.stdout = stdoutProxy(self.appendPlainText)
188 result = eval(command, self.namespace, self.namespace)
190 self.appendPlainText(repr(result))
192 exec command in self.namespace
196 traceback_lines = traceback.format_exc().split('\n')
197 # Remove traceback mentioning this file, and a linebreak
199 traceback_lines.pop(i)
200 self.appendPlainText('\n'.join(traceback_lines))
201 sys.stdout = tmp_stdout
204 def keyPressEvent(self, event):
205 if event.key() == QtCore.Qt.Key_Tab:
209 self.hide_completions()
211 if event.key() in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return):
214 if event.key() == QtCore.Qt.Key_Home:
215 self.setCursorPosition(0)
217 if event.key() == QtCore.Qt.Key_PageUp:
219 elif event.key() in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Backspace):
220 if self.getCursorPosition() == 0:
222 elif event.key() == QtCore.Qt.Key_Up:
223 self.setCommand(self.getPrevHistoryEntry())
225 elif event.key() == QtCore.Qt.Key_Down:
226 self.setCommand(self.getNextHistoryEntry())
228 elif event.key() == QtCore.Qt.Key_L and event.modifiers() == QtCore.Qt.ControlModifier:
231 super(Console, self).keyPressEvent(event)
235 def completions(self):
236 cmd = self.getCommand()
237 lastword = re.split(' |\(|\)',cmd)[-1]
238 beginning = cmd[0:-len(lastword)]
240 path = lastword.split('.')
241 ns = self.namespace.keys()
247 obj = self.namespace.get(path[0])
248 prefix = path[0] + '.'
254 if x[0] == '_':continue
256 if xx.startswith(lastword):
257 completions.append(xx)
260 self.hide_completions()
261 elif len(completions) == 1:
262 self.hide_completions()
263 self.setCommand(beginning + completions[0])
266 p = os.path.commonprefix(completions)
267 if len(p)>len(lastword):
268 self.hide_completions()
269 self.setCommand(beginning + p)
271 self.show_completions(completions)
274 welcome_message = '''
275 ---------------------------------------------------------------
276 Welcome to a primitive Python interpreter.
277 ---------------------------------------------------------------
280 if __name__ == '__main__':
281 app = QtGui.QApplication(sys.argv)
282 console = Console(startup_message=welcome_message)
283 console.updateNamespace({'myVar1' : app, 'myVar2' : 1234})
285 sys.exit(app.exec_())