6

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.

Frying Pan
  • 167
  • 2
  • 8

2 Answers2

2

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

  • 2
    I don't want the actual value to be in the code since I'll be pushing this to a public GitHub. If I do `os.environ['REDDIT_NAME'] = 'something'`, won't that expose the value of `'something'`? – Frying Pan Mar 15 '21 at 02:04
  • 1
    you can using dotenv lib. And push your value to an file and ignore it when push to git. `import dotenv dotenv.load_dotenv(os.path.join(os.path.dirname(__file__), './.env'))` in .env file: REDDIT_NAME = something – Phạm Ngọc Quý Mar 15 '21 at 02:06
1

Install the following packages.

!pip install --quiet openai python-dotenv

Create a .env file like this:

/content# cat .env
OPENAI_API_KEY="sk-*"
OPENAI_ORGANIZATION="org-*"
/content# 

In Colab, it can be read as an environment variable in the following cell.

import dotenv
dotenv.load_dotenv('./.env')

You can hide it as an environment variable and assign it to the variable.

import os
import openai
openai.api_key = os.environ["OPENAI_API_KEY"]
Keiku
  • 8,205
  • 4
  • 41
  • 44