简体   繁体   English

f = open()/可在命令行中使用,但不能作为CGI脚本[python]

[英]f = open() / works in command line but not as CGI script [python]

    #! /usr/bin/env python

import htmlSplitter, htmlGlue

headerContent, mainContent, sideSetup, sideContent, footerContent = htmlSplitter.split("../htdocs/bcc/register.html")


mainContent = "<h1>This is another Test</h1>"
sideContent = "<h2>Jonathan's here!</h2>"


htmlDoc = htmlGlue.glue(headerContent, mainContent, sideSetup, sideContent, footerContent)

f = open("../bcc/doctest.html", "w")
f.write(htmlDoc)
f.close()

print("Location:../bcc/doctest.html")
print

this script works perfectly when I run it from the command line. 当我从命令行运行该脚本时,它可以完美运行。 However, when I run it as a CGI script, it gives me a "premature end of script headers" error. 但是,当我将其作为CGI脚本运行时,它给我一个“脚本头过早结束”的错误。 I've debugged and it's fine if I comment out the segment that opens and writes "doctest.html" (so I know that the other two modules I've included are not causing the problem). 我已经调试了,如果我注释掉打开并写“ doctest.html”的段,那就很好了(因此,我知道我包含的其他两个模块都不会引起问题)。 Any idea why that part of the code doesn't work as a CGI script? 知道为什么该部分代码不能作为CGI脚本工作吗? Is there something I should be substituting instead? 我应该代替什么吗?

NOTE: I've done a chmod a+rw on 'doctest.html' to make sure that the script has permissions to edit. 注意:我已经在doctest.html上执行了chmod a + rw,以确保脚本具有编辑权限。

Thanks! 谢谢!

Maybe just a copy/paste-error, but your shebang seems to be indented. 也许只是复制/粘贴错误,但您的shebang似乎已缩进。 unindent it, and try to start the script via command line on the server, using ./yourscript (not python yourscript , as this is how it probably gets executed by the webserver) 取消缩进,然后尝试使用./yourscript (不是python yourscript通过服务器上的命令行启动脚本,因为这可能是由网络服务器执行的

Add the following to the beginning of your script: 将以下内容添加到脚本的开头:

#!/usr/bin/env python
print 'Content-Type: text/html'
print

I've always declared the Content-Type in my python cgi scripts, it's polite. 我一直在python cgi脚本中声明Content-Type ,这很客气。

import cgi
import cgitb
cgitb.enable() # allows error tracebacks

cgitb will show you a nice web based traceback if something went wrong with your script, such as any exceptions thrown. 如果您的脚本出了问题,例如抛出任何异常, cgitb会向您展示基于Web的不错的追溯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM