正确处理logging.config.fileConfig抛出的IOError?

这可能是一个开放式或尴尬的问题,但我发现自己陷入了越来越多的异常处理问题,我不知道处理它们的“最佳”方法。

如果您尝试使用不存在的文件配置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个IO错误。

这是做这件事的正确方法吗? 有没有更好,更Python的方式,我不知道或不明白?


这不是特定于日志模块的事情:通常,Python代码不会自动为您自动创建中间目录; 你需要使用os.makedirs()明确地做到这一点,通常是这样的:

if not os.path.exists(dirname):
    os.makedirs(dirname)

您可以用记录提供的标准FileHandler替换您所需的检查的子类,并在必要时使用os.makedirs()创建日志文件的目录。 然后,您可以在配置文件中指定此处理程序,而不是标准处理程序。


假设只需要在应用程序执行开始时执行一次,那么我只需os.makedirs()即可,不需要先检查它们的存在,或者甚至等待日志记录模块发出错误。 如果您尝试启动记录器时出现错误,则可以按照您可能已经执行的方式进行处理:打印错误,禁用记录器。 您试图创建该目录,超越了自己的想法。 如果用户给你提供虚假信息,那么你的情况并不比现在差,而且在绝大多数情况下你都会更好。

链接地址: http://www.djcxy.com/p/9279.html

上一篇: Properly handling IOError thrown by logging.config.fileConfig?

下一篇: I need to write a Python script to sort pictures, how would I do this?