为什么每次Python脚本运行时都会给我一个错误?

为什么每次Python脚本运行时都会给我一个错误?,python,json,apache,Python,Json,Apache,我检查了服务器日志,似乎找不到任何解释它为什么这样做的东西。每次加载页面时,我都会收到一条“500内部服务器错误”消息。我要做的就是更新一个JSON文件 #!/usr/bin/env python import cgi import json new_data = {"2": {"title": "what", "date": "tomorrow"}} with open("jobs.json") as file: data = json.load(file) data.upda

我检查了服务器日志,似乎找不到任何解释它为什么这样做的东西。每次加载页面时,我都会收到一条“500内部服务器错误”消息。我要做的就是更新一个JSON文件

#!/usr/bin/env python

import cgi
import json

new_data = {"2": {"title": "what", "date": "tomorrow"}}

with open("jobs.json") as file:
    data = json.load(file)

data.update(new_data)

with open('test.json', 'w') as file:
    json.dump(data, file)

在发送任何内容之前,您需要先发送一些内容类型标题,从:

“常规”编程和CGI编程之间有两个主要区别

首先,CGI程序的所有输出必须以 MIME类型标题。这是告诉客户端排序的HTTP头 它正在接收的内容的数量。大多数情况下,这看起来像:

Content-type: text/html
所以它会是这样的:

#!/usr/bin/env python

import cgi
import json
import sys

new_data = {"2": {"title": "what", "date": "tomorrow"}}

# print "Content-type: application/json\r\n\r\n" to the output stream
sys.stdout.write("Content-type: application/json\r\n\r\n") # read the comment

with open("jobs.json") as file:
    data = json.load(file)

data.update(new_data)

with open('test.json', 'w') as file:
    json.dump(data, file)

还要检查这些文件的路径,以及您是否写入可写目录。

对我很有用。只需确保
jobs.json
位于运行python脚本的同一目录中。您是否尝试使用
cgib.enable()
打开跟踪?为什么不更新我的json呢?@DougSmith这可能与路径和/或正确访问有关,尝试写入可写目录的完整路径。打印应以
\n\n
结尾,而不是上面的内容。@BSH-您是对的,我忽略了隐式
\n
。但是
\r
仍然不正确。@Robᵩ 实际上,正确的形式是
\r\n\r\n