Is it possible to set environment variables in Google's Colaboratory?
Asked Answered
S

2

9

I am running some Python scripts in Google's Colaboratory platform. Now, I need to set some environment variables of the system. Like the following shows:

!export PATH=drive/app/tf-models-fork/research;drive/app/tf-models-fork/research/object_detection;drive/app/tf-models-fork/research/slim;$PATH

I tried to add the location to the variable PATH. However, I am getting the following errors:

/bin/sh: 1: drive/app/tf-models-fork/research/object_detection: Permission denied
/bin/sh: 1: drive/app/tf-models-fork/research/slim: Permission denied
/bin/sh: 1: drive/app/tf-models-fork/research: Permission denied

Is there any way to set the environment variables in this platform?

Swagger answered 6/4, 2018 at 2:48 Comment(2)
The answer below suggesting os.environ is definitely the right approach. But if you're curious, the export line above is failing because you did ; instead of : when appending to the existing path.Jara
Oh yes, you are right! I will also test this correct version of "export" way. Thanks for correcting me for my mistaken!Swagger
E
17

I normally set the PATH with os.environ, like this:

import os
os.environ['PATH'] += ":/usr/local/go/bin"
Eparchy answered 6/4, 2018 at 3:15 Comment(0)
S
0

For PATH environment variables, such as PYTHONPATH, I use sys.path.insert or sys.path.append.

You have these 2 options because sys.path is a list of strings (paths), thus you can either insert or append more strings.

For example,

If you want to insert a new path at index 0:

import sys
sys.path.insert(0,'/path/to/folder')

If you want to append a new path:

import sys
sys.path.append('/path/to/folder')
Shwa answered 11/9, 2018 at 21:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.