我想在浏览器中显示python脚本中的html。如何运行此脚本以便我可以在浏览器中查看此脚本。 代码到目前为止:
index.py
### to run python in browser i have added below lines
#!/usr/bin/env python
header = open("header.html", "r")
print header
和我的 header.html
<!DOCTYPE html>
<html>
<head>
<title>A Python To Do list</title>
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
答案 0 :(得分:2)
Bassically你可以像这样使用BaseHTTPServer并运行你的代码。
localhost.py
#!/usr/bin/env python
import BaseHTTPServer
class HTTPFrontend(object) :
def __init__(self, port) :
self.server = BaseHTTPServer.HTTPServer(('', port), self.RequestHandler)
print "Web interface listening on http://localhost:" + str(port)
def start(self) :
self.server.serve_forever()
def stop(self) :
self.server.socket.close()
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler) :
def do_GET(self) :
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
templateFile = open("home.html")
template = templateFile.read()
templateFile.close()
message = "this is how simple templating works"
self.wfile.write(template % {'message': message})
def do_POST(self) :
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write("this is a POST")
if __name__ == "__main__":
server = HTTPFrontend(8080)
server.start()
home.html的
<html>
<head>
<title>Python | Home</title>
</head>
<body>
%(message)s
</body>
</html>
如果您在浏览器中打开http://localhost:8654
,则会获得:
this is how simple templating works