Test if notebook is running on Google Colab

2020-04-02 07:20发布

问题:

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.

回答1:

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


回答2:

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