Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的KeyError_Python_Html_Cgi_Traceback_Keyerror - Fatal编程技术网

Python中的KeyError

Python中的KeyError,python,html,cgi,traceback,keyerror,Python,Html,Cgi,Traceback,Keyerror,这是我的代码: 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

这是我的代码:

    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

简单的解决方案,如果您不希望它突然出现:

try:
    ViewerType=form['ViewerType'].value
except KeyError:
    pass
这是可行的,但我建议您调试代码并找出出现KeyError的原因。从


首次调用脚本呈现页面时,
表单
dict为空。只有当用户实际提交表单时,才能填写dict。因此,将HTML更改为

众筹
帮不上忙

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

#/usr/bin/env python
导入cgi
form=cgi.FieldStorage()
打印“内容类型:text/html\n\n”
打印“”
打印“”\
请输入查看器类型:
""" #查看器类型 打印“查看器类型” 打印“”\ 众筹 保险费 """ #按一下按钮 打印“”\ """ 打印“” 如果len(形式)>0: ViewerType=form['ViewerType'].value 打印'ViewerType='+ViewerType+'

' 其他: 打印“尚未选择查看器类型” 打印“”
谢谢你,伙计,我用你的代码作为灵感,让它工作起来了。太棒了!谢谢你的意见。另外,我希望您的实际程序没有提供缺少结束标记的HTML,等等:)
try:
    ViewerType=form['ViewerType'].value
except KeyError:
    pass
Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.