如何在带输入参数的shell脚本函数中嵌入python c多行脚本

2024-10-04 05:34:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个shell脚本函数和一个输入参数。在函数中,我嵌入了python多行脚本,它只在python中打印值并导出到shell变量

我尝试将python脚本嵌入到directshell脚本中,但没有将其放入函数中,也没有传递任何输入参数。问题在于如何将shell变量传递给函数中的python脚本

getValues(){ 名称=$1 回音$name python -c ' import .. value="" for .. for key in .. if "${name}" in key.tags: value=str(key["tag"]) break; print(value)' }你知道吗

导出环境=getValues Environment 出口产品=getValues Product

我期望实际结果像dev/stage(从值打印)一样,但shell中得到的是空字符串

我做错什么了吗

注意:我使用了'`'作为expr来调用代码中的shell表达式,但它没有在这里的代码部分打印出来


Tags: key函数代码nameinimport脚本名称
1条回答
网友
1楼 · 发布于 2024-10-04 05:34:27

你可以让pythonstdin读出来

$ cat emb.bash
getvalues(){
    name="$1"
python - <<EOF
data = {'key': 'foo'}
x = [1,2,3,4,5,'$name']
for k in x:
    if k == data.get('key'):
        print(k)
    else:
        print('Nope')
EOF
}

getvalues foo

输出:

$ bash emb.bash
Nope
Nope
Nope
Nope
Nope
foo

另外,您应该注意到有一个名为jqjq的实用程序,它将帮助您读取json文件

相关问题 更多 >