【问题标题】:Write formatted JSON to file using Python使用 Python 将格式化的 JSON 写入文件
【发布时间】:2019-03-23 15:35:28
【问题描述】:

我想使用 shell 脚本将格式化(即缩进)JSON 配置文件写入远程计算机。

我的代码:

json_config = {
    "api-listen": true, 
    "api-network": true, 
    "multi-version": "1", 
    "pools": [
        {
            "pass": "123", 
            "url": "antpool.com:3333"
        }, 
        {
            "pass": "123", 
            "url": "antpool.com:443"
        }, 
        {
            "pass": "123", 
            "antpool.com:25"
        }
    ]
}

# format the new configuration
json_config_formatted = json.dumps(json.dumps(json_config), indent=4)

# write the new config
connection.sendShell('echo "{}" | cat > "/config/bmminer.conf"'.format(json_config_formatted))

但是,所有内容都写在一行上。如何保留字符串的格式?

【问题讨论】:

  • connection 的实例是什么?有没有办法直接为cat设置标准输入?
  • 如果您使用的是subprocess.Popen,例如,您可能会使用p = Popen(["ssh", remote_host, "cat > /config/bmminer.conf"], stdin=PIPE),后跟json.dump(json_config, p.stdin)catssh 继承其标准输入。

标签: python shell


【解决方案1】:

首先,您调用了 json.dumps 两次,因此您正在创建一个本身包含 JSON 的 JSON 字符串。

其次,你应该用 Python 编写文件,而不是 shell。

json_config = {
    ...
}

# format the new configuration
with open("/config/bmminer.conf", "w") as conf:
    json.dump(json_config, conf, indent=4)

对于远程计算机,如何正确获取数据取决于您的库。我不知道sendShell是什么。

【讨论】:

  • sendShell 将数据发送到我通过 SSH 连接的远程计算机。所以,我实际上可以用 Python 写入文件。
  • 如果您告诉我们您从哪里获得 sendShell,我们可以阅读文档并帮助您找到以您需要的方式使用它的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多