Par*_*ker 2 html python printing cgi
我一直在教自己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>"
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果我有一个大的HTML文件,我想在python中显示(它有代码行和代码行,并且里面有JS)我是否必须在每行前面手动添加'print'并将其转换为"等?或者是否有可以为我转换它的方法或脚本?
谢谢!
Ale*_*lli 10
如果调用那个大的html文件(例如)'foo.html'并存在于CGI脚本的当前目录中,那么你需要的只是脚本的主体:
print "Content-type: text/html"
print
with open('foo.html') as f:
print f.read()
Run Code Online (Sandbox Code Playgroud)
如果您坚持使用Python 2.5,请添加from __future__ import with_statement为模块正文的开头.如果你坚持使用更旧的Python,请将最后两行更改为
print open('foo.html').read()
Run Code Online (Sandbox Code Playgroud)
请注意,import cgi当您不使用cgi模块的任何功能时,您不需要这样做,在您的示例和此答案中都是如此.
Ign*_*ams 10
Python支持多行字符串,因此您可以在一个大的模糊中打印出您的文本.
print '''<html>
<head><title>My first Python CGI app</title></head>
<body>
<p>Hello, 'world'!</p>
</body>
</html>'''
Run Code Online (Sandbox Code Playgroud)
它们支持所有字符串操作,包括方法(.upper(),.translate()等)和格式(%),以及原始模式(r前缀)和uunicode前缀.