Solution
Here is an approach to use specific Python Version customizing google colab kernel through Miniconda.
Workable Timestamp: 4/10/2025
I will demonstrate below how to create a Python 3.9 environment within google colab using Miniconda.
Here are steps
Create the google colab file under specific folder.
Here I create custom_env_colab/py-3.9.ipynb upder the root folder of gcloud for demonstrating.
In the file py-3.9.ipynb, we create four cells like below
Cell 1: Specify Parameters
# Parameters
%env PYTHONPATH =
YOUR_GOOGLE_DRIVE_FOLDER = "custom_env_colab"
PYTHON_VERSION = "3.9"
# Connect to google drive place
from google.colab import drive
drive.mount('/content/drive')
# Forward to working dir
import os
os.chdir(f"/content/drive/MyDrive/{YOUR_GOOGLE_DRIVE_FOLDER}")
Cell 2: Build virtulenv with Miniconda
!wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh
!sudo chmod +x Miniconda3-latest-Linux-x86_64.sh
!./Miniconda3-latest-Linux-x86_64.sh -b -f -p /usr/local
!conda update --yes conda
import sys
sys.path.append(f'/usr/local/lib/python{PYTHON_VERSION}/site-packages')
!conda create -n myenv python={PYTHON_VERSION} --yes
!apt-get install libtinfo5 # Fix
Cell 3: Attach to virtualenv and install package
%%shell
eval "$(conda shell.bash hook)"
conda activate myenv
python -m pip install scikit-learn
# python -m pip install -r your-requirements.txt
Cell 4: Execute your own code like below:
%%shell
eval "$(conda shell.bash hook)"
conda activate myenv
python your-code.py
However this method has limitations.
With this method, you need to activate the created environment at the start of each cell execution, which is equivalent to running your command in the terminal.
i.e. Cell will be like below to execute your code:
%%shell
eval "$(conda shell.bash hook)"
conda activate myenv
python main.py
environment.ymlfile to create an environment definition. See here and here for examples and details. (Be aware the notes can be a little outdated.) I don't have a very current conda version I can point you are but these two versions usingrequirements.txt...