How do I set environment variables in Google Colab?

Viewed 2475

On my local computer, I can simply go into "System Properties -> Environment Variables" and add a new variable with its value in user variables.

Then, I can retrieve this value by using this in Python:

import os
os.environ["VAR_NAME"]

However, I just recently started using Google Colab, and it seems it's not able to detect the environment variable, as it gives me this error:

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-36-28128554cf91> in <module>()
      1 import os
----> 2 os.environ["REDDIT_NAME"]

/usr/lib/python3.7/os.py in __getitem__(self, key)
    679         except KeyError:
    680             # raise KeyError with the original key value
--> 681             raise KeyError(key) from None
    682         return self.decodevalue(value)
    683 

KeyError: 'REDDIT_NAME'

How should I go about so that Google Colab can detect my user environment variables? Is there a specific path I need to modify?

Thanks.

1 Answers

Like this

import os
os.environ['REDDIT_NAME'] = 'something'
print(os.getenv('REDDIT_NAME'))

Or using dotenv lib. Keep environment in a file:

  import dotenv
  dotenv.load_dotenv(os.path.join(os.path.dirname(__file__), './.env'))

in .env file: REDDIT_NAME = something

and ignore .env file when push to git

Related