xpt
xpt

Reputation: 22984

Jupyter Notebook to set environment variable from bash subprocess

In Jupyter Notebook, we can use

% bash to run cell with bash in a subprocess.

For example:

%%bash
export PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "${PROJECT}

Can such exported environment variable be used in the next cell? What would this next cell's output be? (sorry I've run out of the allocated time in my GCP Project and cannot validate it myself)

%%bash
echo New $PROJECT

If not, then,

Is there any way to put the environment variable within bash subprocess to Jupyter Notebook's?

Upvotes: 1

Views: 1110

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295272

You can't export variables from one bash cell to another (that isn't a child), but you can export from your Python parent process to bash.

import os, subprocess

# set a Python variable 'project'
project = subprocess.check_output(['gcloud', 'config', 'list', 'project',
                                   '--format', 'value(core.project)'])

# Copy it to an environment variable 'PROJECT'
os.environ['PROJECT'] = project

Upvotes: 2

Related Questions