4

There're many kinds of Python REPL, like the default REPL, ptpython, ipython, bpython, etc. Is there a way to inspect what current REPL is when I'm already in it?

A little background:
As you may have heard, I made pdir2 to generate pretty dir() printing. A challenge I'm facing is to make it compatible with those third-party REPLs, but first I need to know which REPL the program is running in.

4

3 回答 3

2

好的,终于找到了一个简单但超级可靠的方法:检查sys.modules.

您可以复制和使用的功能。

import sys

def get_repl_type():
    if any('ptpython' in key for key in sys.modules):
        return 'PTPYTHON'
    if any('bpython' in key for key in sys.modules):
        return 'BPYTHON'
    try:
        __IPYTHON__
        return 'IPYTHON'
    except NameError:
        return 'PYTHON'
于 2017-03-15T18:48:54.333 回答
0

您可以尝试从调用堆栈中查找信息。

那些花哨的 REPL 使用他们的启动脚本来初始化。

可以在另一个 REPL 中运行一个 REPL,因此您需要从上到下遍历调用堆栈,直到从 REPL 初始化脚本中找到一帧。

于 2017-03-14T03:16:18.543 回答
0

可能您能做的最好的事情就是查看sys.stdinstdout比较它们的类型。

也许每个解释器也有办法挂钩自定义完成或格式化程序。

于 2017-03-13T14:20:25.123 回答