0

I have a file1.py where

import os
y=os.getenv("num")
print(y)

and another file file2.py

import os
os.environ["num"]="7"

Why is it returning the value None instead of 7. please guide me?

I want to access env varibales values of file1.py from another file file2.py

Ophir Carmi
  • 2,701
  • 1
  • 23
  • 42
Amna
  • 3
  • 3
  • Maybe this could answer your question. https://stackoverflow.com/questions/52449602/how-to-set-environment-variables-in-virtualenv – krish May 15 '23 at 11:51
  • Environment variables aren't *in* any file. They exist in memory, and their values are determined by what code you execute, which is affected by which files you execute as scripts and which files you import. So how exactly are you executing your code? – chepner May 15 '23 at 12:05

2 Answers2

0

For file1.py use:

import os
os.environ['num'] = '7'

For file2.py use:

import os
y = os.environ.get('num')
print(y)
rd51
  • 252
  • 4
  • 11
0

There's a misconception here, os.environ refers to the environment of the process being run. So when you create a new environment variable withos.environ["num"] = 7, you only modify the environment of the current program (file2.py). When you try to access "num" from another process (file1.py), it does not exist.

If you want to store environment variables in a persistent way on your system, have a look at this answer (assuming you're on Windows).

Ebig
  • 91
  • 1
  • 8