Python中的keyror

2024-10-01 09:37:21 发布

您现在位置: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

当我把它提供给浏览器时,错误是:

Traceback (most recent call last): File "/home/nandres/dbsys/mywork/James/mywork/ViewerForm.py", >line 42, in ViewerType=form['ViewerType'].value File "/usr/lib/python2.7/cgi.py", line 541, in >getitem raise KeyError, key KeyError: 'ViewerType'

第42行是我代码的最后一行。在

这个错误实际上并没有影响功能,而且一切正常,但我不想让它突然出现。如有任何建议/见解,我们将不胜感激。在

顺便说一句,我在代码的顶端写着:

^{pr2}$

Tags: 代码inpyformvaluetype错误line
2条回答

第一次调用脚本来呈现页面时,formdict为空。只有当用户实际提交表单时,dict才会被填充。所以把你的HTML改成

<option value="C" selected>Crowd Funding

不会帮助。在

因此,在尝试访问dict之前,您需要测试dict。例如

^{pr2}$

如果你不想让它爆开,简单的解决方案:

try:
    ViewerType=form['ViewerType'].value
except KeyError:
    pass

它可以工作,但我建议您调试代码并找出为什么会得到keyrerror。从https://wiki.python.org/moin/KeyError

^{pr2}$

相关问题 更多 >