update env variable on notebook in VsCode

2024/10/8 13:39:30

I’m working on a python project with a notebook and .env file on VsCode. I have problem when trying to refresh environment variables in a notebook (I found a way but it's super tricky).

My project:

.env file with: MY_VAR="HELLO_ALICE"

test.ipynb file with one cell:

from os import environ
print('MY_VAR = ', environ.get('MY_VAR'))

What I want:

  1. set the env variable and run my notebook (see HELLO_ALICE)
  2. edit .env file: change "HELLO_ALICE" to "HELLO_BOB"
  3. set the env variable and run my notebook (see HELLO_BOB)

What do not work:

  1. open my project in vsCode, open terminal
  2. in terminal run: >> set -a; source .env; set +a;
  3. open notebook, run cell --> I see HELLO_ALICE
  4. edit .env (change HELLO_ALICE TO HELLO_BOB)
  5. restart notebook (either click on restart or close tab and reopen it)
  6. in terminal run: >> set -a; source .env; set +a; (same as step 2)
  7. open notebook, run cell --> I see HELLO_ALICE

So I see twice HELLO_ALICE instead of HELLO_ALICE then HELLO_BOB...

But if it was on .py file instead of notebook, it would have worked (I would see HELLO_ALICE first then HELLO_BOB)

To make it work:

Replace step 5. by: Close VsCode and reopen it

Why it is a problem:

It is super tricky. I'm sure that in 3 month I will have forgotten this problem with the quick fix and I will end up loosing again half a day to figure out what is the problem & solution.

So my question is:

Does anyone know why it works like this and how to avoid closing and reopening VsCode to refresh env variable stored in a .env file on a notebook ?

(Closing and reopening VsCode should not change behavior of code)

Notes:

  • VsCode version = 1.63.2
  • I tired to use dotenv module and load env variable in my notebook (does not work)
  • question: How to set env variable in Jupyter notebook works only if you define your env variables inside notebook
  • this behavior happen only on env variables. For instance if instead a .env file I use a env.py file where i define my env constants as python variables, restarting the notebook will refresh the constants.
Answer

The terminal you open in VSC is not the same terminal ipython kernel is running. The kernel is already running in an environment that is not affected by you changing variables in another terminal. You need to set the variables in the correct environment. You can do that with dotenv, but remember to use override=True. This seems to work:

import dotenv
from os import environ
env_file = '../.env'f = open(env_file,'w')
f.write('MY_VAR="HELLO_ALICE"')
f.close()
dotenv.load_dotenv(env_file, override=True)
print('MY_VAR = ', environ.get('MY_VAR'))f = open(env_file,'w')
f.write('MY_VAR="HELLO_BOB"')
f.close()
dotenv.load_dotenv(env_file, override=True)
print('MY_VAR = ', environ.get('MY_VAR'))
MY_VAR =  HELLO_ALICE
MY_VAR =  HELLO_BOB
https://en.xdnf.cn/q/70117.html

Related Q&A

How do I properly set up flask-admin views with using an application factory?

Im trying to setup flask-admin model views with SQLAlchemy against user and role models. Instead of a function admin view Im getting:ValueError: Invalid model property name <class app.models.Role>…

Django Rest Framework: Correct way to serialize ListFields

Based on the DRF documentation I have a created a list of email_id stored in my model in the following way Models.pyclass UserData(models.Model):emails = models.CharField(max_length=100,blank=False)In…

Flask-SQLAlchemy TimeoutError

My backend configuration is :Ubuntu 12.04 Python 2.7 Flask 0.9 Flask-SQLAlchemy Postgres 9.2Ive got this error message: TimeoutError: QueuePool limit of size 5 overflow 10 reached, connection timed ou…

Making saxon-c available in Python

I have just read that Saxon is now available for Python, and thats just great fun and good, but can anyone write a tutorial on how to make it available for Python/Anaconda/WingIDE or similar? I am use…

How to include multiple interactive widgets in the same cell in Jupyter notebook

My goal is to have one cell in Jupyter notebook displaying multiple interactive widgets. Specifically, I would like to have four slider for cropping an image and then another separate slider for rotati…

SWIG - Problem with namespaces

Im having trouble getting the following simple example to work with SWIG 1.3.40 (and I also tried 1.3.31). The Foo structure comes through as a Python module as long as I dont wrap it in a namespace, b…

Django access to subclasses items from abstract class

class Animal(models.Model):....class Meta:abstract = Trueclass Cat(models.Model, Animal):...class Dog(models.Model, Animal):....I want to be able to return all instances of querysets of all the subclas…

Django BinaryField retrieved as memory position?

Ive written a short unit test with the following code:my_object = MyObject() my_object.data = b12345my_object.save() saved_object = MyObject.objects.first()assert saved_object.data == my_object.datawhe…

difflib.SequenceMatcher isjunk argument not considered?

In the python difflib library, is the SequenceMatcher class behaving unexpectedly, or am I misreading what the supposed behavior is?Why does the isjunk argument seem to not make any difference in this…

PyCharm Code Folding/Outlining Generates Wrong Boundaries

Im having a very frustrating issue with PyCharm in that it does not want to properly outline the code so that blocks fold correctly. Ive looked all over the place and couldnt find any help with this pa…