将bash变量传递给python脚本

前端之家收集整理的这篇文章主要介绍了将bash变量传递给python脚本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
将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
总之,这样做:
...
python -c "import test; test.printfoo('$foo')"
...

更新:

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

...
python -c "import test; test.printfoo('"${foo//\'/\\\'}"');"
...
原文链接:https://www.f2er.com/bash/383962.html

猜你在找的Bash相关文章