0

I have the following Bash script called Test_Vars.sh

#!/bin/bash
#----------------------------------------------------#
#  Environment Variables being used in the process   #
#----------------------------------------------------#
export CLUSTER=cluster-test.cloud
export USERNAME=puser
export PASSWORD=$(echo "bXlQYXNzd29yZAo=" | base64 -d)

echo "CLUSTER: $CLUSTER"
echo "USER: $USERNAME"
echo "PASS: $PASSWORD"

Now my Python Script called test.py that calls the Bash scripts is as follows

#!/usr/bin/env python3

import os

home_dir = os.environ['HOME']
username = os.environ['USER']

print("User " +username +" home Directory is " +home_dir)

from subprocess import call
RC = call("/disk/home/roachd/Scripts/Test_Vars.sh")
cluster = os.environ['CLUSTER']
username = os.environ['USERNAME']
password = os.environ['PASSWORD']

print("Print Variables exported by Bash script Test_Vars.sh")
print("Cluster: " + CLUSTER)
print("User: " + USERNAME)
print("PD: " + str(PASSWORD))

Now when I execute the Python script I get they following result:

User roachd home Directory is /disk/home/roachd
CLUSTER: cluster-test.cloud
USER: puser
PASS: myPassword
Traceback (most recent call last):
  File "test.py", line 12, in <module>
    cluster = os.environ['CLUSTER']
  File "/usr/lib64/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'CLUSTER'

Any help would be greatly appreciated.

2
  • Would print("Cluster: " + str(CLUSTER)) help? Jun 14 '21 at 20:03
  • Sorry about my (deleted) answer; I was answering the wrong question. Jun 14 '21 at 20:39
2

Yeah... You can't do that. Only CHILD processes have access to the environment variables of a PARENT process. You can SET the environment variables for a new child process (depending on how you start it). The default is the parent's own variables.

From an exiting child, you get a integer representing the return status value and you can examine the output. In your script, you print the variables. In python, you can read the output to get those values.

4
  • Okay so then I should initiate the Python code from a Bash script after I have set my Global variables in Bash and then they would be available with any Python code afterwards?
    – roachd
    Jun 15 '21 at 14:20
  • Yes. That is how it is intended to work. NB: you can set variables in your .bashrc to be loaded when you login. You can also set variables in your crontab to be set when your cronjobs run.
    – zBeeble
    Jun 15 '21 at 16:01
  • I tried calling Python from Bash after setting the variables in Bash and that didn't work. Here is the Bash Script:
    – roachd
    Jun 15 '21 at 18:33
  • Did you export your variables in bash? Sounds like you didn't (since it didn't work).
    – zBeeble
    Jun 16 '21 at 20:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.