Skip to main content
seems to do with environment variables, so added the environment-variables tag
Link

Run a Bash Script from Python and import the exported environment variables into Python

Source Link
roachd
  • 11
  • 1
  • 2

Run a Bash Script from Python and import the exported variables into Python

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.