Python 脚本index.py中格式不正确的标头错误的标头

Python 脚本index.py中格式不正确的标头错误的标头,python,apache,Python,Apache,我想在apache2(ubuntu 14.04)服务器上运行python代码。我已按照以下步骤操作并获得错误: 步骤1: 配置1:我已经在下面创建了一个目录和文件 /var/www/cgi-bin 配置2:我已经编辑了/etc/apache2/sites available/000-default.conf Alias /cgi-bin /var/www/cgi-bin <Directory "/var/www/cgi-bin"> Options Indexes FollowSym

我想在apache2(ubuntu 14.04)服务器上运行python代码。我已按照以下步骤操作并获得错误:

步骤1:

配置1:我已经在下面创建了一个目录和文件

/var/www/cgi-bin
配置2:我已经编辑了/etc/apache2/sites available/000-default.conf

Alias /cgi-bin /var/www/cgi-bin
<Directory "/var/www/cgi-bin">
Options Indexes FollowSymLinks ExecCGI
AddHandler cgi-script .cgi .py
Allow from all
</Directory>

<Directory /var/www/cgi-bin>
Options All
</Directory>

您应该以
\r\n
结尾标题,然后必须打印另一个
\r\n
以表示正文即将到来

(换句话说,它将您的身体解释为头部,因为头部从未终止)

试试这个脚本

#/usr/bin/env python
进口cgi;
进口cgib;cgib.enable()
打印“内容类型:文本/html”
打印“”#使用此双引号打印语句在脚本中添加空行
打印“Hello python”

标题和主要html内容之间应该有一行空格。这就是为什么我们必须在脚本中启动html标记之前使用额外的print语句。

当您需要打印文件时,我遇到了刷新机制的问题。 如果http请求是通过apache2调用的,则此代码将响应http请求

导入系统 打印(“内容类型:image/png”,end=“\r\n\r\n”,flush=True) sys.stdout.buffer.write(字节(打开(“file.png”、“rb”).read())
end=“\r\n\r\n”
添加空行以开始正文


flush=True
强制python按预期打印行。在我的例子中,标题打印错误。

对我来说,这确实将HTML代码直接输出到浏览器。我通过将上下文类型:text/plain更改为内容类型:text/htmlSorry,我刚刚编辑了问题中提到的代码。我错过了那里提到的内容类型。我做的和你做的一样。谢谢你提醒我这件事
#!/usr/bin/env python
import cgi;
import cgitb;cgitb.enable()

print "Content-Type: text/plain\n"

print "<b>Hello python</b>"
malformed header from script 'index.py': Bad header: Hello Python
#!/usr/bin/env python
import cgi;
import cgitb;cgitb.enable()

print "Content-Type: text/html"
print "" #use this double quote print statement to add a blank line in the script
print "<b>Hello python</b>"