2013-08-23 57 views
1

嗨,我想從html表單獲取輸入並將其傳遞給我的python腳本並使其執行,然後我想在瀏覽器中打印我的結果而不使用任何框架。下面是我的Python代碼:Python: - 將HTML表單輸入傳遞給python代碼並執行它

import re 

hap=['amused','beaming','blissful','blithe','cheerful','cheery','delighted'] 

sad=['upset','out','sorry','not in mood','down'] 

sad_count=0 

happy_count=0 

str1=raw_input("Enter Message...\n") 

happy_count=len(filter(lambda x:x in str1,hap)) 

sad_count=len(filter(lambda x:x in str1,sad)) 

if(happy_count>sad_count): 

     print("Hey buddy...your mood is HAPPY :-)") 

elif(sad_count>happy_count): 

      print("Ouch! Your Mood is Sad :-(") 

elif(happy_count==sad_count): 

     if(happy_count>0 and sad_count>0): 

      print("oops! You are in CONFUSED mood :o") 

     else: 
      print("Sorry,No mood found :>") 
+0

您需要某種網絡服務器,運行html模板,並創建一個處理代碼的回調函數。看看一些基本的cgi/wsgi [示例](http://wiki.python.org/moin/CgiScripts) – dorvak

回答

4

似乎是你使用python3但是在Python 2.7與BaseHTTPServer(即HTTP.server在python3),你可以做一些事情一樣,

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer 
import cgi 

class Handler(BaseHTTPRequestHandler): 
    def do_GET(self): 
     self.send_response(200) 
     self.end_headers() 
     self.wfile.write(""" 
      <html><head></head> 
      <body> 
      <form method="POST"> 
      your mood: 
      <textarea name="mood"> 
      </textarea> 
      <input type="submit" name="submit" value="submit"> 
      </form> 
      </body> 
      </html> 
      """) 
     return 

    def do_POST(self): 
     form = cgi.FieldStorage(
      fp=self.rfile, 
      headers=self.headers, 
      environ={'REQUEST_METHOD':'POST', 
        'CONTENT_TYPE':self.headers['Content-Type'], 
        }) 
     themood = form["mood"] 
     hap=['amused','beaming','blissful','blithe','cheerful','cheery','delighted'] 
     sad=['upset','out','sorry','not in mood','down'] 
     sad_count=0 
     happy_count=0 
     happy_count=len(filter(lambda x:x in themood.value,hap)) 
     sad_count=len(filter(lambda x:x in themood.value,sad)) 
     if(happy_count>sad_count): 
      self.wfile.write("Hey buddy...your mood is HAPPY :-)") 
     elif(sad_count>happy_count): 
      self.wfile.write("Ouch! Your Mood is Sad :-(") 
     elif(happy_count==sad_count): 
      if(happy_count>0 and sad_count>0): 
       self.wfile.write("oops! You are in CONFUSED mood :o") 
      else: 
       self.wfile.write("Sorry,No mood found :>") 
     return 
server = HTTPServer(('', 8181), Handler) 
server.serve_forever() 

我希望可以幫到你

0

如果你想在你的本地機器上測試它,你可以用python創建一個簡單的web服務器。你可以找到一個很好的教程here。你可以編寫python腳本來處理數據。 或者你應該安裝一個像Apache或NGinx這樣的真正的網絡服務器,並使用cgi或wsgi擴展。第二種方法的優點是,在這種情況下,服務器可以照顧html,css,image等文件,這樣您就可以專注於您的python代碼,並且不需要編寫整個現有的應用程序。