Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing bash variables to a script?

Tags:

python

bash

What's the best way to pass bash variables to a python script. I'd like to do something like the following:

$cat test.sh
#!/bin/bash

foo="hi"
python -c 'import test; test.printfoo($foo)'

$cat test.py
#!/bin/python

def printfoo(str):
    print str

When I try running the bash script, I get a syntax error:

  File "<string>", line 1
    import test; test.printfoo($foo)
                               ^
SyntaxError: invalid syntax
like image 621
Ravi Avatar asked Jul 16 '11 19:07

Ravi


People also ask

How do I pass a variable to another script in bash?

You have basically two options: Make the variable an environment variable ( export TESTVARIABLE ) before executing the 2nd script. Source the 2nd script, i.e. . test2.sh and it will run in the same shell.

How do you pass variables in a script?

Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

How do you pass an argument to a shell script?

Using arguments Inside the script, we can use the $ symbol followed by the integer to access the arguments passed. For example, $1 , $2 , and so on. The $0 will contain the script name.


1 Answers

You can use os.getenv to access environment variables from Python:

import os
import test
test.printfoo(os.getenv('foo'))

However, in order for environment variables to be passed from Bash to any processes it creates, you need to export them with the export builtin:

foo="hi"
export foo
# Alternatively, the above can be done in one line like this:
# export foo="hi"

python <<EOF
import os
import test
test.printfoo(os.getenv('foo'))
EOF

As an alternative to using environment variables, you can just pass parameters directly on the command line. Any options passed to Python after the -c command get loaded into the sys.argv array:

# Pass two arguments 'foo' and 'bar' to Python
python - foo bar <<EOF
import sys
# argv[0] is the name of the program, so ignore it
print 'Arguments:', ' '.join(sys.argv[1:])
# Output is:
# Arguments: foo bar
EOF
like image 100
Adam Rosenfield Avatar answered Oct 11 '22 02:10

Adam Rosenfield