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
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.
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.
$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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With