pythongoogle-colaboratory

Test if notebook is running on Google Colab


How can I test if my notebook is running on Google Colab?

I need this test as obtaining / unzipping my training data is different if running on my laptop or on Colab.


Solution

  • For environments using ipython

    If you are sure that the script will be run using ipython which is the most typical usage, there is also the possibility to check the ipython interpreter used. I think it is a little bit more clear and you don't have to import any module.

    if 'google.colab' in str(get_ipython()):
      print('Running on CoLab')
    else:
      print('Not running on CoLab')
    

    If you need to do it multiple times you might want to assign a variable so you don't have to repeat the str(get_ipython()).

    RunningInCOLAB = 'google.colab' in str(get_ipython())
    

    RunningInCOLAB is True if run in a Google Colab notebook.

    For environments not using ipython

    In this case you have to check ipython is used first, assuming that COLab will always use ipython.

    RunningInCOLAB = 'google.colab' in str(get_ipython()) if hasattr(__builtins__,'__IPYTHON__') else False