5

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.

MarianD
  • 13,096
  • 12
  • 42
  • 54
laike9m
  • 18,344
  • 20
  • 107
  • 140

3 Answers3

3

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'
laike9m
  • 18,344
  • 20
  • 107
  • 140
  • In theory, this will break if you have ptpython installed and `import ptpython` before running this method. The presence of a module in `sys.modules` is not conclusive evidence that the current code is being called by it :). The only conclusive way to check would be to inspect the callstack. – vikarjramun Aug 31 '22 at 18:15
0

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.

languitar
  • 6,554
  • 2
  • 37
  • 62
0

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.

Liteye
  • 2,761
  • 1
  • 16
  • 16