エラーと警告の両方の詳細を伝達する共通のパターンはありますか? エラー私はコードの流れを止める原因となる深刻な問題を意味します。 warnings私は問題をユーザーに知らせることができますが、プログラムの流れを止めるにはあまりにも些細な問題を意味します。エラーと警告の両方の詳細を伝達するパターンはありますか?
私は現在、ハードエラーを処理するための例外と、警告を記録するPythonロギングフレームワークを扱います。しかし、今は代わりに現在処理中のレコードのデータベースフィールドに警告を記録したいと思います。私は、例外と同じ方法で警告をバブルアップしたいが、プログラムの流れを止めることはないと思う。
>>> import logging
>>>
>>> def process_item(item):
... if item:
... if item == 'broken':
... logging.warning('soft error, continue with next item')
... else:
... raise Exception('hard error, cannot continue')
...
>>> process_item('good')
>>> process_item(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in process_item
Exception: hard error, cannot continue
>>> process_item('broken')
WARNING:root:soft error, continue with next item
この例(と私の現在の問題は)Pythonであるが、それはあまりにも例外を除いて、他の言語に適用されるべきです。
Davidの提案と、以下の例との短いプレー後、Pythonのwarnings
モジュールは、移動するための方法です。
import warnings
class MyWarning(Warning):
pass
def causes_warnings():
print 'enter causes_warnings'
warnings.warn("my warning", MyWarning)
print 'leave causes_warnings'
def do_stuff():
print 'enter do_stuff'
causes_warnings()
causes_warnings()
causes_warnings()
print 'leave do_stuff'
with warnings.catch_warnings(record=True) as w:
# Cause all warnings to always be triggered.
warnings.simplefilter("always")
# Trigger a number of warnings.
do_stuff()
# Do something (not very) useful with the warnings generated
print 'Warnings:',','.join([str(warning.message) for warning in w])
出力:
enter do_stuff
enter causes_warnings
leave causes_warnings
enter causes_warnings
leave causes_warnings
enter causes_warnings
leave causes_warnings
leave do_stuff
Warnings: my warning,my warning,my warning
注:Pythonのcatch_warnings
のために必要とされる2.6+。
参考までに解決策を投稿するのではなく、質問に編集するよりも、解決策を投稿するほうがよいでしょう。 –
私は自分のコメントをあなたのコメントとして書いておきたいと思いますが、コメントの中でうまく書式設定することはできません。 – Mat
フォローアップのために+1 – jfs