1

I need to source an environment file/Unix script from Python script to fetch the variables and use those variables in Python script.

I am able to source the environment file/Unix script but not able to fetch the value of the variable and use it.

My env file (env_var.env)looks like:-

export FLAG=YES; export TAG=A;

I want to source this file in my python script and need to print and use the values of FLAG and TAG.

Thanks in advance.

AbhinavVaidya8
  • 522
  • 6
  • 18
  • 2
    So you do not want to source the file in your shell and then read the environment in Python, but to source the file _in Python_? That's a lot more difficult than the first way. – nnnmmm Feb 06 '18 at 17:15
  • 3
    Possible duplicate of [Access environment variables from Python](https://stackoverflow.com/questions/4906977/access-environment-variables-from-python) - I'm guessing you mean you just want to access the environment variables. – kabanus Feb 06 '18 at 17:16
  • No, this env file will contain the environment variables and well the other variables like Folder_Path which could be /a/b/c. – AbhinavVaidya8 Feb 06 '18 at 17:38
  • You should probably parse it. Do you really need to run it through bash? – Josh Lee Feb 06 '18 at 17:39
  • @nnnmmm, I want to read the environment file directly from the Python script. – AbhinavVaidya8 Feb 06 '18 at 17:39
  • I tried creating a wrapper using Unix shell script and called my python script inside that wrapper script. This allowed me to source the variables using os.environ. – AbhinavVaidya8 Feb 10 '18 at 22:01

2 Answers2

1

To solve this I am created an Unix wrapper on top of my python script and source all the variables in that wrapper. I was able to import all the variables in python script.

AbhinavVaidya8
  • 522
  • 6
  • 18
1

Try the following:

import os

os.system("source env_var.env && print(FLAG) && print(TAG)")
Salma Elshahawy
  • 1,112
  • 2
  • 11
  • 21