将bash变量传递给脚本?

Rav*_*avi 12 python bash

将bash变量传递给python脚本的最佳方法是什么?我想做类似以下的事情:

$cat test.sh
#!/bin/bash

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

$cat test.py
#!/bin/python

def printfoo(str):
    print str
Run Code Online (Sandbox Code Playgroud)

当我尝试运行bash脚本时,出现语法错误:

  File "<string>", line 1
    import test; test.printfoo($foo)
                               ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

Ada*_*eld 13

您可以使用os.getenv从Python访问环境变量:

import os
import test
test.printfoo(os.getenv('foo'))
Run Code Online (Sandbox Code Playgroud)

但是,为了将环境变量从Bash传递到它创建的任何进程,您需要使用export内置导出它们:

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
Run Code Online (Sandbox Code Playgroud)

作为使用环境变量的替代方法,您只需在命令行上直接传递参数即可.-c commandget加载到sys.argv数组后传递给Python的任何选项:

# 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
Run Code Online (Sandbox Code Playgroud)


ssa*_*ota 8

简而言之,这有效:

...
python -c "import test; test.printfoo('$foo')"
...
Run Code Online (Sandbox Code Playgroud)

更新:

如果您认为字符串可能包含'@Gordon在下面的注释中所说的单引号(),那么您可以在bash中轻松地转义那些单引号.在这种情况下,这是另一种解决方案:

...
python -c "import test; test.printfoo('"${foo//\'/\\\'}"');"
...
Run Code Online (Sandbox Code Playgroud)

  • 如果$ foo在文字中包含任何单引号或其他字符python解释,这将很有趣.@ Adam的解决方案更强大...... (2认同)