繁体   English   中英

这个python代码做什么?

[英]What does this python code do?

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部分,无需解释其余部分,我仅将其余部分添加为上下文)

该代码大致等同于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',)
  • 请注意,它会覆盖文件,但不会附加文件。

它打开一个名为logfile.txt ,并将与异常关联的消息写入其中。

尝试返回dictionary [name]的值。 如果失败,则将错误写入外部文件。

它将异常写入logfile.txt。

%s替换为e(这是Exception字符串表示形式)

\\ n是换行符。

它会“尝试”从字典中返回值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM