Test if notebook is running on Google Colab

后端 未结 4 1248
小蘑菇
小蘑菇 2021-01-07 19:47

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

相关标签:
4条回答
  • 2021-01-07 19:58

    you can check environment variable like this:

    import os
    if 'COLAB_GPU' in os.environ:
       print("I'm running on Colab")
    

    actually you can print out os.environ to check what's associated with colab and then check the key

    0 讨论(0)
  • 2021-01-07 20:08

    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.

    0 讨论(0)
  • 2021-01-07 20:10

    Try importing google.colab

    try:
      import google.colab
      IN_COLAB = True
    except:
      IN_COLAB = False
    

    Or just check if it's in sys.modules

    import sys
    IN_COLAB = 'google.colab' in sys.modules
    
    0 讨论(0)
  • 2021-01-07 20:19

    In a %%bash cell, use:

    %%bash
    [[ ! -e /colabtools ]] && exit  # Continue only if running on Google Colab
    
    # Do Colab-only stuff here
    

    Or in Python equivalence

    import os
    if os.path.exists('/colabtools'):
      # do stuff
    
    0 讨论(0)
提交回复
热议问题