将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
当我尝试运行bash脚本时,出现语法错误:
File "<string>", line 1
import test; test.printfoo($foo)
^
SyntaxError: invalid syntax
答案 0 :(得分:12)
您可以使用os.getenv
从Python访问环境变量:
import os
import test
test.printfoo(os.getenv('foo'))
但是,为了将环境变量从Bash传递到它创建的任何进程,您需要使用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
作为使用环境变量的替代方法,您可以直接在命令行上传递参数。 -c command
加载到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
答案 1 :(得分:8)
简而言之,这有效:
...
python -c "import test; test.printfoo('$foo')"
...
<强>更新强>
如果您认为字符串可能包含@Gordon在下面的评论中所说的单引号('
),您可以在bash中轻松地转义这些单引号。在这种情况下,这是另一种解决方案:
...
python -c "import test; test.printfoo('"${foo//\'/\\\'}"');"
...
答案 2 :(得分:2)
你必须使用双引号来获取bash中的变量替换。与PHP类似。
$ foo=bar
$ echo $foo
bar
$ echo "$foo"
bar
$ echo '$foo'
$foo
因此,这应该有效:
python -c "import test; test.printfoo($foo)"
答案 3 :(得分:2)
使用argv处理。这样您就不必导入它,然后从解释器运行它。
test.py
import sys
def printfoo(string):
print string
if __name__ in '__main__':
printfoo(sys.argv[1])
python test.py testingout