为我的PyQt应用程序协调ipythonqt控制台

2024-05-29 00:16:07 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我看到了一些问题:this one讨论了如何在应用程序中嵌入ipythonqt小部件和传递函数,尽管看起来这些函数在IPython内核中执行,而不是在主应用程序的内核中执行。还有一个this guy,但是我不能执行示例中的代码(它已经两年了),而且它看起来也不像我想要的那样。在

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


Tags: 方法函数应用程序绘图部件ipython关键字传递函数
1条回答
网友
1楼 · 发布于 2024-05-29 00:16:07

这就是我想到的,到目前为止,它运行得很好。我子类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

示例命令:

^{pr2}$

相关问题 更多 >

    热门问题