简体   繁体   English

将 bash 变量传递给脚本?

[英]Passing bash variables to a script?

What's the best way to pass bash variables to a python script.将 bash 变量传递给 python 脚本的最佳方法是什么。 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:当我尝试运行 bash 脚本时,出现语法错误:

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

You can use os.getenv to 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 theexport builtin :但是,为了将环境变量从 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

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

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.如果您认为字符串可能包含@Gordon 在下面的评论中所说的单引号( ' ),您可以在 bash 中轻松转义这些单引号。 Here's a alternative solution in that case:在这种情况下,这是一个替代解决方案:

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

Do it with argv handling.用 argv 处理来做。 This way you don't have to import it then run it from the interpreter.这样您就不必导入它然后从解释器中运行它。

test.py测试.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.您必须使用双引号来获取 bash 中的变量替换。 Similar to PHP.类似于 PHP。

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

Thus, this should work:因此,这应该有效:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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