Reputation: 19388
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.
Upvotes: 5
Views: 443
Reputation: 19388
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'
Upvotes: 3
Reputation: 2801
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.
Upvotes: 0
Reputation: 6794
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.
Upvotes: 0