【发布时间】:2021-09-08 23:04:01
【问题描述】:
我在尝试从 QPlainTextEdit 中执行字符串/文件时遇到了一些问题,这似乎是某种范围问题。发生的情况是,当代码 EXECUTABLE_STRING 从全局范围运行时,它可以正常工作。但是,当它从本地范围运行时,例如通过 AbstractPythonCodeWidget,它要么找不到要继承的对象TypeError: super(type, obj): obj must be an instance or subtype of type,要么遇到名称错误NameError: name 'Test' is not defined。根据exec(EXECUTABLE_STRING) 行在运行时是否被注释/取消注释,这会发生奇怪的变化。任何帮助将不胜感激。
import sys
from PyQt5.QtWidgets import QApplication, QPlainTextEdit
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor
app = QApplication(sys.argv)
EXECUTABLE_STRING = """
from PyQt5.QtWidgets import QLabel, QApplication
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QCursor
class Test(QLabel):
def __init__(self, parent=None):
super(Test, self).__init__(parent)
self.setText("Test")
a = Test()
a.show()
a.move(QCursor.pos())
"""
class AbstractPythonCodeWidget(QPlainTextEdit):
def __init__(self, parent=None):
super(AbstractPythonCodeWidget, self).__init__(parent)
self.setPlainText(EXECUTABLE_STRING)
def keyPressEvent(self, event):
if event.modifiers() == Qt.ControlModifier:
if event.key() == Qt.Key_Return:
# this does not work
#exec(compile(self.toPlainText(), "script", "exec"), globals(), locals())
exec(self.toPlainText())
return QPlainTextEdit.keyPressEvent(self, event)
w = AbstractPythonCodeWidget()
w.show()
w.move(QCursor.pos())
w.resize(512, 512)
# this works when run here, but not when run on the keypress event
# exec(EXECUTABLE_STRING)
sys.exit(app.exec_())
【问题讨论】:
-
您是否正在尝试创建自己的测试环境,您可以在其中编写和编辑代码,然后进行动态测试?如果是这样,有这样做的策略。我不建议从应用程序内部编辑代码;相反,您可以像往常一样继续使用您的编辑器,并在您的测试应用程序中构建重新加载功能。这样做的机制already exists,很有帮助!
-
更广泛地说——事实上,
exec是完成这项工作的正确工具的次数不为零,但它们很少而且相差甚远。始终谨慎对待,并寻找其他选择。 -
所以,我使用
exec只是为了我知道如何使用它。应用程序的更广泛范围是在应用程序内部,用户可以创建 Python 脚本,然后可以在触发某些事件时运行这些脚本。用户的脚本可以是原始字符串,也可以是磁盘上的实际文件,具体取决于他们设置的设置。所以我不太确定实时编码示例会有多大帮助,但我会去看看。
标签: python inheritance pyqt exec