使用子进程调用时卷曲不起作用

Curl not working when called with subprocess

我正在尝试使用 curl 调用 REST api。 api端点是在程序中动态生成的,同时上传了一个json文件。

with open('data.json','w') as f:
    f.write(json.dumps(data))
    cmd = 'curl -X PUT -H "Content-Type: application/json" -d @data.json {0}'.format(put_uri)
    print cmd
    p= subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    p.wait()
    output, errors = p.communicate()
    if p.returncode != 0:
        print "Request failed"

我在这里打印形成的命令,当我 运行 来自 shell 的命令时,它正在按预期工作。但是相同的命令是 运行,Popen 会抛出一些 json 验证错误,这很奇怪

{
  "success" : false,
  "message" : "Resource cannot be parsed due to Unexpected character ('/' (code 47)): maybe a (non-standard) comment? (not recognized as one since Feature 'ALLOW_COMMENTS' not enabled for parser)\n at [Source: java.io.StringReader@444c7495; line: 1, column: 2]"
}

此代码无法确保 JSON 在调用 curl 之前完全写入磁盘。

f.write(json.dumps(data)) 之后使用 f.flush()f.close()