Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import bash variables from a python script

I have seen plenty examples of running a python script from inside a bash script and either passing in variables as arguments or using export to give the child shell access, I am trying to do the opposite here though.

I am running a python script and have a separate file, lets call it myGlobalVariables.bash

myGlobalVariables.bash:

foo_1="var1"    
foo_2="var2"   
foo_3="var3"  

My python script needs to use these variables.

For a very simple example:

myPythonScript.py:

print "foo_1: {}".format(foo_1)

Is there a way I can import them directly? Also, I do not want to alter the bash script if possible since it is a common file referenced many times elsewhere.

like image 845
Bagelstein Avatar asked Feb 23 '26 19:02

Bagelstein


2 Answers

If your .bash file is formatted as you indicated - you might be able to just import it direct as a Python module via the imp module.

import imp
bash_module = imp.load_source("bash_module, "/path/to/myGlobalVariables.bash")
print bash_module.foo_1
like image 60
theorifice Avatar answered Feb 25 '26 10:02

theorifice


You can also use os.environ:

Bash:

#!/bin/bash
# works without export as well
export testtest=one

Python:

#!/usr/bin/python
import os
os.environ['testtest']  # 'one'
like image 30
Marat Avatar answered Feb 25 '26 10:02

Marat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!