Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting if ipython notebook is outputting to a terminal

I want to detect if a Jupyter Notebook is being executed in a terminal e.g. via ipython --TerminalIPythonApp.file_to_run command, as opposite to a HTML enabled notebook. Note that this is different from detecting if the Python code is run with python or within a notebook.

Based on this I can format Pandas DataFrames suitable either for HTML or for terminal display.

How can I detect if a notebook is outputting to a terminal?

like image 325
Mikko Ohtamaa Avatar asked Feb 02 '26 14:02

Mikko Ohtamaa


1 Answers

This might help.

from IPython import get_ipython
def type_of_execution():
    try:
        type_of_exec = str(type(get_ipython()))
        if 'terminal' in type_of_exec:
            return 'terminal'
        elif 'zmqshell' in type_of_exec:
            return 'jupyter'
        else:
            return 'python'
    except:
        return 'terminal likely'
print("Checking..")
print(type_of_execution())
like image 198
William Avatar answered Feb 04 '26 06:02

William



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!