5from __future__
import print_function
21from highlighter
import PythonHighlighter, QtQmlHighlighter
24 from PyQt6.QtQml
import (
25 QScriptEngine, QScriptValue, QScriptValueIterator)
27 from PyQt5.QtQml
import (
28 QScriptEngine, QScriptValue, QScriptValueIterator)
33 def __init__(self, parent=None, readonly=True, max_rows=1000, echo=True):
34 QPlainTextEdit.__init__(self, parent)
36 self.setReadOnly(readonly)
37 self.document().setMaximumBlockCount(max_rows)
41 sys.stdout = sys.stderr = self
47 sys.stdout = sys.__stdout__
48 sys.stderr = sys.__stderr__
52 sys.__stdout__.write(s)
54 cursor = QTextCursor(doc)
55 cursor.clearSelection()
56 cursor.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.MoveAnchor)
58 cursor.movePosition(QTextCursor.MoveOperation.End, QTextCursor.MoveMode.MoveAnchor)
59 cursor.clearSelection()
60 self.ensureCursorVisible()
61 QApplication.instance().processEvents()
64 self.
write(
"\n".join(lines))
69 def __init__(self, parent=None, ps1="?", ps2=">"):
70 OutputWidget.__init__(self, parent, readonly=
False)
71 self.setTabChangesFocus(
False)
77 print(self.
ps1, end=
'')
81 OutputWidget.focusInEvent(self, event)
91 cursor = self.textCursor()
92 cursor.select(QTextCursor.SelectionType.BlockUnderCursor)
93 cursor.removeSelectedText()
95 modifiers = event.modifiers()
97 line = unicode(self.document().end().previous().text())
98 ps1orps2, line = line[:l - 1], line[l:]
100 if not key
in [Qt.Key.Key_Tab, Qt.Key.Key_Backtab]
and \
103 if key == Qt.Key.Key_Up:
109 elif key == Qt.Key.Key_Down:
115 elif key == Qt.Key.Key_Tab:
116 if modifiers & Qt.KeyboardModifier.ControlModifier:
117 print(
" " * 4, end=
'')
122 print(ps1orps2, end=
'')
123 print(self.completer.complete(line, self.
tab_state)
or line, end=
'')
124 elif key == Qt.Key.Key_Backtab:
129 print(ps1orps2, end=
'')
130 print(self.completer.complete(line, self.
tab_state)
or line, end=
'')
131 elif key
in [Qt.Key.Key_Backspace, Qt.Key.Key_Left]:
132 if self.textCursor().columnNumber() > len(ps1orps2) + 1:
133 return OutputWidget.keyPressEvent(self, event)
134 elif key == Qt.Key.Key_Return:
135 self.moveCursor(QTextCursor.MoveOperation.EndOfLine, QTextCursor.MoveMode.MoveAnchor)
138 print(self.
ps2, end=
'')
140 print(self.
ps1, end=
'')
145 return OutputWidget.keyPressEvent(self, event)
150 def __init__(self, name="<pyqtshell>", locals=None):
156 def run(self, source, locals=None):
159 code = compile(source, self.
name,
"exec")
165 Scripter.activeWindow.redraw =
True
166 Scripter.activeWindow.update()
173 self.
lines.append(line)
176 line =
"\n".join(self.
lines) +
"\n"
181 code = compile(line, self.
name,
"single")
183 except SyntaxError
as why:
184 if why[0] ==
"unexpected EOF while parsing":
185 self.
lines.append(line)
197 Scripter.activeWindow.redraw =
True
198 Scripter.activeWindow.update()
205 if sys.exc_info()[0] == SyntaxError:
206 print(
" File \"%s\", line %d" % (self.
name, sys.exc_value[1][1]))
207 print(
" " * (sys.exc_value[1][2] + 2) +
"^")
208 print(str(sys.exc_info()[0]) +
":", sys.exc_value[0])
210 traceback.print_tb(sys.exc_info()[2],
None)
211 print(sys.exc_type.__name__ +
":", sys.exc_info()[1])
235 for list
in [keyword.kwlist,
236 __builtin__.__dict__,
239 if word[:n] == text
and word !=
"__builtins__":
244 def get_class_members(cls):
246 if hasattr(cls,
'__bases__'):
247 for base
in cls.__bases__:
248 ret = ret + get_class_members(base)
251 m = re.match(
r"(\w+(\.\w+)*)\.(\w*)", text)
254 expr, attr = m.group(1, 3)
257 if hasattr(object,
'__class__'):
258 words.append(
'__class__')
259 words = words + get_class_members(object.__class__)
263 if word[:n] == attr
and word !=
"__builtins__":
264 matches.append(
"%s.%s" % (expr, word))
271 ConsoleWidget.__init__(self, parent, ps1=
">>> ", ps2=
"... ")
284 doc = self.document()
297 engine = QScriptEngine()
298 ns = engine.globalObject()
299 for name, value
in self.
locals.items():
300 if isinstance(value, QObject):
301 value = engine.newQObject(value)
302 elif callable(value):
303 value = engine.newFunction(value)
304 ns.setProperty(name, value)
312 result = engine.evaluate(code)
314 Scripter.activeWindow.redraw =
True
315 Scripter.activeWindow.update()
318 if engine.hasUncaughtException():
319 bt = engine.uncaughtExceptionBacktrace()
321 print(
"\n".join([
" %s" % l
for l
in list(bt)]))
322 print(engine.uncaughtException().toString())
324 if not result.isUndefined():
325 print(result.toString())
376 'decodeURIComponent',
378 'encodeURIComponent',
426 it = QScriptValueIterator(self.
engine.globalObject())
433 words.extend(js_words)
445 ConsoleWidget.__init__(self, parent, ps1=
">>> ", ps2=
"... ")
447 namespace = namespace
or {}
449 def console_print(context, engine):
450 for i
in range(context.argumentCount()):
451 print(context.argument(i).toString(), end=
'')
453 return QScriptValue()
455 def dir_context(context, engine):
456 if context.argumentCount() == 0:
457 obj = context.thisObject()
459 obj = context.argument(0)
461 it = QScriptValueIterator(obj)
464 l.append(str(it.name()))
465 return QScriptValue(engine, repr(l))
466 namespace[
"print"] = console_print
467 namespace[
"dir"] = dir_context
468 namespace[
"Application"] = QApplication.instance()
470 namespace[
"Scripter"] = Scripter.qt
480if __name__ ==
"__main__":
481 app = QApplication(sys.argv)
__init__(self, namespace)
complete(self, text, state)
global_matches(self, text)
__init__(self, parent=None, namespace=None)
run(self, source, locals=None)
__init__(self, name="<pyqtshell>", locals=None)
complete(self, text, state)
global_matches(self, text)
__init__(self, parent=None, namespace=None)
execute_code(self, code, engine=None)