例外のトラップと記録

トラップしたくないエラーがある時の記述例でもある。

>>> import io, traceback
>>> def process_all_files(all_filenames,fatal_exceptions=(KeyboardInterrupt, MemoryError)):
	bad_filenames = {}
	for one_filename in all_filenames:
		try:
			# 宣言されていないが、具体的なファイル処理
			process_one_file(one_filename)
		# 引数で渡されている致命的なエラータイプ
		except fatal_exceptions:
			raise
		# それ以外のエラートラップと記録
		except Exception:
			# python3でcStringIOモジュールはio.StringIO,io.BytesIOになったらしい
			f = io.StringIO()
			traceback.print_exc(file=f)
			bad_filenames[one_filename] = f.getvalue()
	return bad_filenames

>>> for x,y in process_all_files(('a','b','c')).items():
	print(x,y)

a Traceback (most recent call last):
  File "<pyshell#26>", line 5, in process_all_files
NameError: global name 'process_one_file' is not defined

c Traceback (most recent call last):
  File "<pyshell#26>", line 5, in process_all_files
NameError: global name 'process_one_file' is not defined

b Traceback (most recent call last):
  File "<pyshell#26>", line 5, in process_all_files
NameError: global name 'process_one_file' is not defined