gpt4 book ai didi

python - 为我的 PyQt 应用程序选择 IPython Qt 控制台

转载 作者:行者123 更新时间:2023-11-30 23:12:22 25 4
gpt4 key购买 nike

我正在使用 Python 创建一个控制台驱动的 Qt 应用程序。我不想实现自己的自定义控制台,而是想嵌入 IPython Qt 控制台,同时使其响应我的应用程序。例如,我希望将某些关键字输入到控制台来触发我的主应用程序中的操作。因此,我在控制台中输入“dothis”,然后在应用程序的另一个窗口中显示了一个绘图。

我看到了一些类似的问题:this one讨论如何将 IPython Qt 小部件嵌入到您的应用程序中并传递函数,尽管看起来这些函数在 IPython 内核中执行,而不是在我的主应用程序的内核中执行。还有this guy ,但我无法执行示例中的代码(它已经有两年了),而且它看起来也没有做我想要的事情。

有没有一种方法可以传递将在我的主内核中执行的函数或方法,或者至少通过与 IPython 内核通信以某种方式模拟这种行为?以前有人这样做过吗?

最佳答案

这是我想出来的,到目前为止效果很好。我对 RichIPythonWidget 类进行子类化并重载 _execute 方法。每当用户在控制台中输入内容时,我都会根据注册命令列表进行检查;如果它与命令匹配,那么我执行命令代码,否则我只是将输入传递给默认的 _execute 方法。

控制台代码:

from IPython.qt.console.rich_ipython_widget import RichIPythonWidget

class CommandConsole( RichIPythonWidget ):
"""
This is a thin wrapper around IPython's RichIPythonWidget. It's
main purpose is to register console commands and intercept
them when typed into the console.

"""
def __init__(self, *args, **kw ):
kw['kind'] = 'cc'
super(CommandConsole, self).__init__(*args, **kw)
self.commands = {}


def _execute(self, source, hidden):
"""
Overloaded version of the _execute first checks the console
input against registered commands. If it finds a command it
executes it, otherwise it passes the input to the back kernel
for processing.

"""
try:
possible_cmd = source.split()[0].strip()
except:
return super(CommandConsole, self)._execute("pass", hidden)

if possible_cmd in self.commands.keys():
# Commands return code that is passed to the console for execution.
s = self.commands[possible_cmd].execute()
return super(CommandConsole, self)._execute( s, hidden )
else:
# Default back to the original _execute
return super(CommandConsole, self)._execute(source, hidden)


def register_command( self, name, command ):
"""
This method links the name of a command (name) to the function
that should be called when it is typed into the console (command).

"""
self.commands[name] = command

示例命令:

from PyQt5.QtCore import pyqtSignal, QObject, QFile

class SelectCommand( QObject ):
"""
The Select command class.

"""
# This signal is emitted whenever the command is executed.
executed = pyqtSignal( str, dict, name = "selectExecuted" )

# This is the command as typed into the console.
name = "select"

def execute(self):
"""
This method is executed whenever the ``name`` command is issued
in the console.

"""
name = "data description"
data = { "data dict" : 0 }
# The signal is sent to my Qt Models
self.executed.emit( name, data )
# This code is executed in the console.
return 'print("the select command has been executed")'

关于python - 为我的 PyQt 应用程序选择 IPython Qt 控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29857569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com