Skip to content Skip to sidebar Skip to footer

How To Pass Bash Variables As Python Arguments

I'm trying to figure out if it is possible to pass values stored in a variable in Bash in as argument values in a python script. We have a python script that we use to create DNS r

Solution 1:

Yes, seems to work just fine to me.

To test, I threw together a very quick python script called test.py:

#!/usr/bin/pythonimport sys

print'number of arguments: ', len(sys.argv)
#we know sys.argv[0] is the script name, let's look at sys.argv[1]print sys.argv[1]

Then, in your terminal, set a variable:

>testvar="TESTING"

And try your script, passing the variable into the script:

>python test.py $testvar>number of arguments: 2>TESTING

Admittedly I'm not very well-versed in Python, but this did seem to accomplish what you wanted. That said, this assumes the Python script you referenced is already set up to parse the names of the parameters being passed to it - you'll notice my test script does NOT do that, it simply spits out whatever you pass into it.

Solution 2:

As long as the variables are exported, they're accessible from Python.

$ export VAR=val$ python -c "import os; print os.environ['VAR']"
val

Post a Comment for "How To Pass Bash Variables As Python Arguments"