2

I am trying to access constants set in a python file from a bash script. The constants will be accessed by both python files and bash scripts. At first I thought to just set the variables in python like:

import os
...
constant_variable=1
constant_path='/path/to/file'

etc...

and then

source constants_file.py

in the bash script.

but I have been told to set these constants as environmental variables in python instead as the python file will likely include stuff that I don't want to load into bash using "source" in the future.

I have tried doing something like this in python...

os.environ['CONSTANT_VARIABLE'] = '1'
...

constant_variable = int(os.environ.get('CONSTANT_VARIABLE'))

and then accessing it in bash like so...

constant_variable=${CONSTANT_VARIABLE}

which does not work because I am no longer using source to read in the constants from the python file...

I don't know if this is even possible, but is there some way to just import env variables created by the python file without sourcing the whole file? Or am I way off base here?

Thanks!

thebaconator
  • 223
  • 6
  • 10
  • Does this answer your question? [python export env variable in Linux shell](https://stackoverflow.com/questions/51886448/python-export-env-variable-in-linux-shell) – ti7 Jul 12 '21 at 17:34
  • Hello, my first call will be putting it in a file which is « sourceable ». – Funkynene Jul 12 '21 at 17:35
  • @ti7 hmm.. but then if I export the python file from bash to create the env variables, wont that still load in the extra stuff that I don't want? Starting to think this is just going to be a mess doing it this way... maybe a better overall question would be, is there a way that I can check in python if the file is being sourced from a bash script? And then if so I only bring in the stuff that is relevant? – thebaconator Jul 12 '21 at 17:45

1 Answers1

0

If you set the environment variable in python, it will only be set for the process's child process. Unless you're running the bash script FROM the python process, you'll probably need to either generate a file to source with bash, or just define the variables in bash and then read them in python.

Sobhan
  • 333
  • 2
  • 8