How to know from python script if we are in jupyterlab

Hi,
I would like to be able to know how to know programmatically if my script is being executed in juypterlab.
I would like to be able to distinguish between these two situations:

  1. script running in ipykernel non-jupyterlab
  2. script running in jupyterlab.

Is there a function I can exploit, or how can I write it?
Thank you in advance

Depends on what you mean by running in jupyterlab. Assuming “in a notebook/console with ipykernel in jupyterlab” GitHub - jtpio/ipylab: Control JupyterLab from Python Notebooks with Jupyter Widgets 🧪 ☢️ 🐍 could help. But there are many other ways to execute a script from jupyterlab (via terminal, via scheduler, etc).

1 Like

Thank you for your response.
I would like to be able to define whether a py script is being executed by JupyterLab or not.

I give below an imaginary example. I want to be able to do so:

import IPython

def whereami():
    if IPython.utils.is_jupyterlab(): # <- invented function
        print("I'm running from JupyterLab")
        my_function_for_JL()
    else:
        my_other_function()
    return

I give another example.
If I wanted to put a script among the startup scripts, I would want it to activate certain functions only if it is run in jupyterlab.

Is it possible to do this? Are there utility functions from IPython or some module in the jupyter stack?

Thank you in advance

I mean it is probably not just ticking in lab but this is what i can come up with:

import os

if 'JPY_PARENT_PID' in os.environ:
    print('Oh ya jupyter.')
else:
    print('No run in jupyter')

thank you. This actually do the trick!

It would be great if there was some more robust core function, so that we would not fear that this variable would be removed someday. Anyway great!