[英]KeyError in Python
這是我的代碼:
print """\
<form method="post">
Please enter Viewer Type:<br />
<table>
"""
#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"
print """\
<option value="C">Crowd Funding
<option value="P">Premium
"""
#do it button
print """\
<input type="submit" value="OK" />
"""
print """\
</form>
</body>
<html>
"""
ViewerType=form['ViewerType'].value
而且,當我將其提供給瀏覽器時,會出現以下錯誤:
追溯(最近一次通話最近):文件“ /home/nandres/dbsys/mywork/James/mywork/ViewerForm.py”,>第42行,在ViewerType = form ['ViewerType']。value文件中,“ / usr / lib / python2.7 / cgi.py“,第541行,在> getitem中引發KeyError ,關鍵KeyError:“ ViewerType”
第42行是我代碼的最后一行。
該錯誤實際上並沒有影響功能,並且一切正常,但是我真的不希望它彈出。 任何建議/見解將不勝感激。
順便說一句,我在代碼的頂部:
import cgi
form = cgi.FieldStorage()
首次調用腳本以呈現頁面時, form
dict為空。 僅當用戶實際提交表單時,該字典才會被填充。 因此,將您的HTML更改為
<option value="C" selected>Crowd Funding
不會幫助。
因此,在嘗試訪問字典之前,需要先對其進行測試。 例如,
#! /usr/bin/env python
import cgi
form = cgi.FieldStorage()
print 'Content-type: text/html\n\n'
print "<html><body>"
print """\
<form method="post">
Please enter Viewer Type:<br />
<table>
"""
#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"
print """\
<option value="C">Crowd Funding
<option value="P">Premium
"""
#do it button
print """\
<input type="submit" value="OK" />
"""
print "</table></form>"
if len(form) > 0:
ViewerType = form['ViewerType'].value
print '<p>Viewer Type=' + ViewerType + '</p>'
else:
print '<p>No Viewer Type selected yet</p>'
print "</body></html>"
如果您不希望彈出的簡單解決方案:
try:
ViewerType=form['ViewerType'].value
except KeyError:
pass
它將起作用,但我建議您調試代碼並找出為什么得到KeyError的原因。 從https://wiki.python.org/moin/KeyError ,
Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.