Can I load environment variables set in a python file to a bash script?

Viewed 245

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!

1 Answers

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.

Related