Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add the path to PYTHONPATH in google colab

how to execute the following command in google colab. export PYTHONPATH=/project/pylib/src:$PYTHONPATH

!export PYTHONPATH=/project/pylib/src:$PYTHONPATHit is not affect.

like image 811
Alpace Avatar asked May 19 '19 12:05

Alpace


Video Answer


2 Answers

Edit 2020-11-12

Using `%` instead of `!` retains any changes to all cells in the session. So, we can use that to set the environment variable `PYTHONPATH`. However, export doesn't work in colab. `%env` can be used to set the environment variable.
! echo $PYTHONPATH
%env PYTHONPATH="$/env/python:/content/gdrive/My Drive/Colab Notebooks/MNIST_Classifier/src"
! echo $PYTHONPATH

Output:

/env/python
/env/python:/content/gdrive/My Drive/Colab Notebooks/MNIST_Classifier/src

Initial Answer

The following worked for me
! echo $PYTHONPATH

import os
os.environ['PYTHONPATH'] += ":/content/gdrive/My Drive/Colab Notebooks/MNIST_Classifier/src"

! echo $PYTHONPATH

Output:

/env/python
/env/python:/content/gdrive/My Drive/Colab Notebooks/MNIST_Classifier/src

Sources:
https://medium.com/@omernaeem/you-can-set-environment-variables-using-os-environ-78a5181b6376
https://stackoverflow.com/a/49684719/3337089

like image 147
Nagabhushan S N Avatar answered Oct 24 '22 04:10

Nagabhushan S N


The answer depends on why you want to do this.

For example, if you want to add the path to your current Python session so that Python's import mechanism finds modules located in that directory, you can do this:

import sys
sys.path.insert(1, "/project/pylib/src")

If you want to modify the environment variable itself (which won't affect the paths used in your current Python session) you can use the %set_env magic:

%set_env PYTHONPATH=/project/pylib/src:/env/python
like image 9
jakevdp Avatar answered Oct 24 '22 04:10

jakevdp