How to inspect the type of REPL you're using?

372 views Asked by At

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.

3

There are 3 answers

1
laike9m On BEST ANSWER

Ok, finally found a simple but super reliable way: checking sys.modules.

A function you could copy and use.

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'
0
languitar On

Probably the best you can do is to look at sys.stdin and stdout and compare their types.

Maybe there are also ways for each interpreter to hook in custom completions or formatters.

0
Liteye On

You can try to find information from the call stack.

Those fancy REPLs use their startup script to initialize.

It's possible to run one REPL in another, so you need to traverse call stack from top to bottom until find a frame from REPL init script.