該代碼大致相當於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',)
來源
2012-03-21 02:38:16
wim
它記錄異常。 'log.write('%s \ n'%e)'意味着'寫一些東西給文件,並用'e'作爲寫出來的東西。它被稱爲字符串格式。 – birryree 2012-03-21 02:37:39
換句話說,你的問題是「log.write()的這個參數是什麼意思?」你最好問一個更具體的問題。 「這個代碼做什麼?」是非常含糊和通用的。 – jhocking 2012-03-21 02:37:41
你*嘗試過*嗎? – 2012-03-21 03:28:44