bash 将bash变量传递给脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6719549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing bash variables to a script?
提问by Ravi
What's the best way to pass bash variables to a python script. I'd like to do something like the following:
将 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
When I try running the bash script, I get a syntax error:
当我尝试运行 bash 脚本时,出现语法错误:
File "<string>", line 1
import test; test.printfoo($foo)
^
SyntaxError: invalid syntax
采纳答案by ssapkota
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:
如果您认为字符串可能包含单引号('),正如@Gordon 在下面的评论中所说,您可以在 bash 中很容易地转义这些单引号。在这种情况下,这里有一个替代解决方案:
...
python -c "import test; test.printfoo('"${foo//\'/\\'}"');"
...
回答by Adam Rosenfield
You can use os.getenvto access environment variables from Python:
您可以使用os.getenv从 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 exportbuiltin:
但是,为了将环境变量从 Bash 传递到它创建的任何进程,您需要使用exportbuiltin导出它们:
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 commandget loaded into the sys.argvarray:
作为使用环境变量的替代方法,您可以直接在命令行上传递参数。在-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
回答by Jakob Bowyer
Do it with argv handling. This way you don't have to import it then run it from the interpreter.
使用 argv 处理来完成。这样你就不必导入它然后从解释器运行它。
test.py
测试文件
import sys
def printfoo(string):
print string
if __name__ in '__main__':
printfoo(sys.argv[1])
python test.py testingout
回答by H?vard
You have to use double quotes to get variable substitution in bash. Similar to PHP.
您必须使用双引号来获取 bash 中的变量替换。类似于 PHP。
$ foo=bar
$ echo $foo
bar
$ echo "$foo"
bar
$ echo '$foo'
$foo
Thus, this should work:
因此,这应该有效:
python -c "import test; test.printfoo($foo)"

