これはオープンエンドまたは厄介な質問かもしれませんが、それらを処理するための「最良の」アプローチがわからないという例外処理の問題にますます遭遇していることに気づきました。
存在しないファイルで FileHandler を構成しようとすると、Python のログ モジュールは IOError を発生させます。モジュールはこの例外を処理せず、単に発生させます。多くの場合、ファイルへのパスが存在しない (したがってファイルが存在しない) ため、例外を処理して続行するには、パスに沿ってディレクトリを作成する必要があります。
すべてのユーザーが、適切なディレクトリを作成しない理由を尋ねてきたので、アプリケーションでこのエラーを適切に処理したいと考えています。
これを処理することにした方法を以下に示します。
done = False
while not done:
try:
# Configure logging based on a config file
# if a filehandler's full path to file does not exist, it raises an IOError
logging.config.fileConfig(filename)
except IOError as e:
if e.args[0] == 2 and e.filename:
# If we catch the IOError, we can see if it is a "does not exist" error
# and try to recover by making the directories
print "Most likely the full path to the file does not exist, so we can try and make it"
fp = e.filename[:e.rfind("/")]
# See http://stackoverflow.com/questions/273192/python-best-way-to-create-directory-if-it-doesnt-exist-for-file-write#273208 for why I don't just leap
if not os.path.exists(fp):
os.makedirs(fp)
else:
print "Most likely some other error...let's just reraise for now"
raise
else:
done = True
構成する必要がある N 個の FileHandlers があるため、このシナリオで発生させて修正する必要がある N 個の IOErrors があるため、ループ (または再帰) する必要があります。
これはこれを行う適切な方法ですか?私が知らない、または理解できない可能性のある、より良い、よりPython的な方法はありますか?