在 Python CGI 中打印 HTML
我一直在自学 python 和 cgi 脚本,我知道你的基本脚本看起来像
#!/usr/local/bin/python
import cgi
print "Content-type: text/html"
print
print "<HTML>"
print "<BODY>"
print "HELLO WORLD!"
print "</BODY>"
print "</HTML>"
我的问题是,如果我有一个大的 HTML 文件,我想在 python 中显示(它有一行又一行的代码和一些 JS) )我是否必须在每行前面手动添加“print”并将“s 转换为 \”等?或者有没有一种方法或脚本可以为我转换它?
谢谢!
I've been teaching myself python and cgi scripting, and I know that your basic script looks like
#!/usr/local/bin/python
import cgi
print "Content-type: text/html"
print
print "<HTML>"
print "<BODY>"
print "HELLO WORLD!"
print "</BODY>"
print "</HTML>"
My question is, if I have a big HTML file I want to display in python (it had lines and lines of code and sone JS in it) do I have to manually add 'print' in front of each line and turn "s into \" , etc? Or is there a method or script that could convert it for me?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Python 支持多行字符串,因此您可以在一篇大的简介中打印出文本。
它们支持所有字符串操作,包括方法(
.upper()
、.translate()
等)和格式化(%
),如下以及原始模式(r
前缀)和u
unicode 前缀。Python supports multiline strings, so you can print out your text in one big blurb.
They support all string operations, including methods (
.upper()
,.translate()
, etc.) and formatting (%
), as well as raw mode (r
prefix) and theu
unicode prefix.那个大 html 文件被称为(例如)
'foo.html'
并位于 CGI 脚本的当前目录中,那么您所需的脚本主体就是:如果 Python 2.5,添加
from __future__ import with_statement
作为模块主体的开头。如果您坚持使用更旧的 Python,请将最后两行更改为注意,当您不使用
cgi< 的任何功能时,您不需要
import cgi
/code> 模块,您的示例和本答案中都是这种情况。If that big html file is called (for example)
'foo.html'
and lives in the current directory for your CGI script, then all you need as your script's body is:If you're stuck with Python 2.5, add
from __future__ import with_statement
as the start of your module's body. If you're stuck with an even older Python, change the last two lines intoNote that you don't need to
import cgi
when you're using none of the functionality of thecgi
module, which is the case both in your example and in this answer.当我第一次尝试装饰器时,我编写了这个小CGI装饰器来处理HTML头部和身体标记样板内容。这样您就可以编写:
调用时返回:
然后可以从 HTTP 服务器的
do_GET
或do_POST
方法调用say_hello
。When I was first experimenting with decorators, I wrote this little CGI decorator to handle the HTML head and body tag boilerplate stuff. So that you can just write:
which when called returns:
Then
say_hello
could be called from your HTTP server'sdo_GET
ordo_POST
methods.Python 支持多行字符串。因此,您只需复制 HTML 代码并将其粘贴到引用中即可。
等等!
Python supports multiline string. So you can just copy your HTML code and paste it into the quotations.
and so on!