简体   繁体   中英

Passing bash variables to a script?

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 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 theexport 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

In short, this works:

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

Update:

If you think the string may contain single quotes( ' ) as said by @Gordon in the comment below, You can escape those single quotes pretty easily in bash. Here's a alternative solution in that case:

...
python -c "import test; test.printfoo('"${foo//\'/\\\'}"');"
...

Do it with argv handling. This way you don't have to import it then run it from the interpreter.

test.py

import sys

def printfoo(string):
    print string

if __name__ in '__main__':
    printfoo(sys.argv[1])

python test.py testingout

You have to use double quotes to get variable substitution in bash. Similar to PHP.

$ foo=bar
$ echo $foo
bar
$ echo "$foo"
bar
$ echo '$foo'
$foo

Thus, this should work:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM