def getvalue(dictionary, name):
try:
return dictionary[name]
except Exception as e:
log = open('logfile.txt', 'w')
log.write('%s\n' % e)
log.close()
这段代码有什么作用? (我理解除了log.write部分之外的所有部分,不需要解释其余部分,我只是为上下文添加了其余部分)
答案 0 :(得分:2)
此代码大致相当于dictionary.get(name)
,但在查找不存在的密钥的情况下,不存在的密钥的名称也会写入文件logfile.txt
。与dict.get
类似,在这种情况下,函数将返回对象None
,异常将不重新引发。
您可以通过在口译员中进行试验来清理自己:
>>> d = {'some_key_which_exists': 'some_value'}
>>> d['some_key_which_exists']
'some_value'
>>> d['some_key_which_does_not_exist']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'some_key_which_does_not_exist'
>>> try:
... d['some_key_which_does_not_exist']
... except Exception as e:
... print '%s\n' % e
...
'some_key_which_does_not_exist'
>>> e
KeyError('some_key_which_does_not_exist',)
答案 1 :(得分:0)
它打开一个名为logfile.txt
的文件,并将与该例外相关的消息写入其中。
答案 2 :(得分:0)
尝试返回字典[name]的值。如果不成功,则将错误写入外部文件。
答案 3 :(得分:0)
它将异常写入logfile.txt。
%s被替换为e(这是异常字符串表示)
\ n是新行字符。
答案 4 :(得分:-1)
它“尝试”从字典中返回值。