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
基本上你不能。使用一些框架,如我們Django,瓶等 – nu11p01n73R 2014-10-10 07:26:01
我主要關注如何在瀏覽器中運行腳本,並感謝您的時間@ nu11p01n73R – 2014-10-10 07:27:31
爲什麼downvote downvoters – 2014-10-10 07:27:53