How to call . /home/test.sh file in python script

Viewed 417

I have file called . /home/test.sh (the space between the first . and / is intentional) which contains some environmental variables. I need to load this file and run the .py. If I run the command manually first on the Linux server and then run python script it generates the required output. However, I want to call . /home/test.sh from within python to load the profile and run rest of the code. If this profile is not loaded python scripts runs and gives 0 as an output.

The call

subprocess.call('. /home/test.sh',shell=True)

runs fine but the profile is not loaded on the Linux terminal to execute python code and give the desired output.

Can someone help?

1 Answers

Environment variables are not inherited directly by the parent process, which is why your simple approach does not work.

If you are trying to pick up environment variables that have been set in your test.sh, then one thing you could do instead is to use env in a sub-shell to write them to stdout after sourcing the script, and then in Python you can parse these and set them locally.

The code below will work provided that test.sh does not write any output itself. (If it does, then what you could do to work around it would be to echo some separator string afterward sourcing it, and before running the env, and then in the Python code, strip off the separator string and everything before it.)

import subprocess
import os

p = subprocess.Popen(". /home/test.sh; env -0", shell=True, 
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE)

out, _ = p.communicate()

for varspec in out.decode().split("\x00")[:-1]:
    pos = varspec.index("=")
    name = varspec[:pos]
    value = varspec[pos + 1:]
    os.environ[name] = value

# just to test whether it works - output of the following should include
# the variables that were set
os.system("env")

It is also worth considering that if all that you want to do is set some environment variables every time before you run any python code, then one option is just to source your test.sh from a shell-script wrapper, and not try to set them inside python at all:

#!/bin/sh
. /home/test.sh
exec "/path/to/your/python/script $@"

Then when you want to run the Python code, you run the wrapper instead.

Related