如何将一个JSON字符串作为输入传递给Python脚本

2024-10-03 02:44:35 发布

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

我正在写一个shell脚本测试.sh在其中我定义了一个json\u str变量

json_str='{"ecommerce": "master","app_compat":"master"}'

我将此变量传递给python脚本命令->

^{pr2}$

在python脚本中,我正在打印输入的值

{"ecommerce":

不是整条线。 我无法更改输入字符串,因为它来自服务器,无法更改。 解决方法是

json_str='{\"\ecommerce": \"\master",\"
\app_compat":\"\master"\}'

你能建议另一种方法来做这个,因为我不能改变输入字符串。在

python脚本内部

input_release=sys.argv[1]

print("here input %s" %input_release)

shell脚本

#!/usr/bin/env bash

echo "Inside bash script"
json_str='{"ecommerce": "master","app_compat":"master"}'

echo "$json_str"
sudo python3 release.py $json_str

Tags: 方法字符串echomaster脚本bashjsonapp
2条回答

问题不在于Python和Json,而在于shell本身。当您向shell输入以下行时:

sudo python3 release.py $json_str

以下是按顺序发生的事情:

  • 变量被其值替换为sudo python3 release.py {"ecommerce": "master","app_compat":"master"
  • 由于:和{}之间的空格,该行被标记为单词:1:sudo2:python33:release.py4:{"ecommerce":5:"master","app_compat":"master",因为:和{}

避免拆分的常见方法是用引号将要替换的变量括起来。不幸的是,您不能在这里这样做,因为字符串已经包含引号。

我只能想象两种解决方案:

  1. 确保替换字符串不包含未经转义的空格(一个\,因为它出现在简单引号内):

    json_str='{"ecommerce":\ "master","app_compat":"master"}'
    
  2. 使用标准输入读取字符串

    Python3:input_release = input()或Python2:input_release = rawinput()

    shell:echo $json_str | sudo python release.py,或使用以下文档:

    sudo python release.py <<END
    $json_str
    END
    

它会因为JSON中的空格而中断。您可以通过引用将其作为单个参数传递:

sudo python3 release.py "$json_str"

但是,如果无法更改CLI,则可以尝试在Python中重新创建:

^{pr2}$

。。。

import sys

json_data = " ".join(sys.argv[1:])
print("JSON data: ", json_data)
# JSON data: {"ecommerce": "master","app_compat":"master"}

尽管要注意的是,您不能用这种方式解释所有的shell扩展,而且CLI并不是真正用于传递大型JSON类结构的,所以为什么不将它作为一个环境变量传递,例如在shell脚本中:

#!/usr/bin/env bash

json_str='{"ecommerce": "master","app_compat":"master"}'

export $json_str
sudo python3 release.py

在Python脚本中:

import os

json_data = os.environ["json_str"]
print("JSON data: ", json_data)
# JSON data: {"ecommerce": "master","app_compat":"master"}

相关问题 更多 >