Load environment variables from shell script

I have a file with some environment variables that I want to use in a python script

The following commands form the command line

$ source myFile.sh $ python ./myScript.py 

and from inside a python script I can access variables like

 import os os.getenv('myvariable') 

How can I install a shell script, then access variables using a python script?

+6
source share
2 answers

If you are talking about a reverse distribution medium, sorry you cannot. This is a security issue. However, the direct source environment from python is definitely valid. But this is more or less a manual process.

 import subprocess as sp SOURCE = 'your_file_path' proc = sp.Popen(['bash', '-c', 'source {} && env'.format(SOURCE)], stdout=sp.PIPE) source_env = {tup[0].strip(): tup[1].strip() for tup in map(lambda s: s.strip().split('=', 1), proc.stdout)} 

Then you have everything you need in source_env .

If you need to write it back to your local environment (which is not recommended since source_env allows you to clear):

 import os for k, v in source_env.items(): os.environ[k] = v 

Another tiny attention needs to be paid here, since I called bash here, you should expect the rules to apply here. Therefore, if you want your variable to be visible, you will need to export them.

 export VAR1='see me' VAR2='but not me' 
+9
source

You can not load environment variables in general from bash or shell script, this is a different language. You will need to use bash to evaluate the file, and then somehow print the variables and then read them. see Forcing bash to expand variables in a line loaded from a file

-2
source

Source: https://habr.com/ru/post/989949/


All Articles