2014-03-06 53 views
0

我試圖運行下面的程序:有cgi.parse()的Python中的等價3

#!/Python33/python 
# Demonstrates get method with an XHTML form. 

import urllib.parse 
import cgi 
import cgitb 
import html 
cgitb.enable() 

def printHeader(title): 
    print("Content-type: text/html; charset=utf-8") 
    print() 
    print("<html>") 
    print("<head><title>Test</title></head>") 
    print("<body>") 
    print(title) 
    print("</body>") 
printHeader("Using 'get' with forms") 
print ('''<p>Enter one of your favorite words here:<br /></p> 
    <form method = "get" action = "method.py"> 
     <p><input type = "text" name = "word"/> 
     <input type = "submit" value = "Submit word"/> 
     </p> 
    </form>''') 
pairs = cgi.parse(); 
if pairs.has_key("word"): 
    print ('''<p>Your word is: 
     <span style = "font-weight: bold">%s</span></p>''') \ 
    % html.escape(pairs[ "word" ][ 0 ]) 
print ("</body></html>") 
print() 

當我運行它,我得到以下錯誤:

22   </p> 
    23 </form>''') 
=> 24 pairs = cgi.parse(); 
    25 if pairs.has_key("word"): 
    26  print ('''<p>Your word is: 
pairs undefined, cgi = <module 'cgi' from 'C:\\Program Files (x86)\\Apache Software Foundation\\Apache2.2\\htdocs\\cgi.py'>, cgi.parse undefined 
AttributeError: 'module' object has no attribute 'parse' 
    args = ("'module' object has no attribute 'parse'",) 
    with_traceback = <built-in method with_traceback of AttributeError object> 

我正在使用Python 3.3,我無法找到是否有替代cgi.parse()我應該使用。

回答

0

cgi.parse exists in python 3.3,但是你有一個名爲cgi.py的python文件,它發現了。

這裏就是嚴重命名cgi.py文件住:

<module 'cgi' from 'C:\\Program Files (x86)\\Apache Software 
Foundation\\Apache2.2\\htdocs\\cgi.py'> 

python 3.3 does not have "has_key" though ...

所以你在這條線得到一個錯誤:

if pairs.has_key("word"): 

更改即:

if "word" in pairs: 

使代碼適合我的工作。

輸出:

Content-type: text/html; charset=utf-8 
<html> 
<head><title>Test</title></head> 
<body> 
Using 'get' with forms 
</body> 
<p>Enter one of your favorite words here:<br /></p> 
    <form method = "get" action = "method.py"> 
     <p><input type = "text" name = "word"/> 
     <input type = "submit" value = "Submit word"/> 
     </p> 
    </form> 
</body></html> 
+0

謝謝你的有用的信息,我是實際上指名爲CGI另一個文件。 – user3386581