One of my new years resolutions this year was to try and replace bash scripting with python in some of my projects. The reasons for this include the ability to use objects to group parameters together.
At today’s (Jan 19, 2025) Python over Coffee meetup, Ricardo suggested that I look at the plumbum library as a tool to help make that transition. In my first hack at using it, I came across an issue: I need to read in environment variables.
We store envvars in a file like this:
export SOC_ID="soc04"
export BASE_TAG="v6.12.1"
export BRANCH_TAG="v6.12.1"
TOPICS_ROOT="linux/6.12.y"
NOTE='
Long note
explaining things.
'
These envvars then need to be passed to the files we execute. Since plumbum does not have the concept of sourcing a file the way that we would in bash, we have to read in the variables directly. Here is a hacky script for reading in the envvars:
#!/bin/python3 from plumbum import local CONF_FILE="config/gen-ac04-v6.12-general.conf" def main(): val="" appending=False with open(CONF_FILE, 'r') as file: for line in file: if appending and line[-1] == "'": appending=False print("%s %s:" % (key, val)) if ("export" in line): line = line.replace('export ', '') words = line.rstrip().split("=") key=words[0] if (words[1] == "'"): appending=True val="" continue elif appending: val=val+ words[1] else: val=words[1] print("%s %s:" % (key, val)) local.env[key]=val print ("Hello") for key, value in local.env.items(): print("key = %s, value=%s" %(key, value)) main() |
I am sure this could be cleaned up significantly, but we also can find a better way to share our environment variables.
The real problem is that our bash scripting is done using functions, and without “source” we have no way to pull those in and execute the individual functions.”