Python:文件处理问题:删除文件时不留.nsx文件

2 投票
2 回答
1443 浏览
提问于 2025-04-17 18:46

我在我的Python程序中有一个处理日志记录的方法。

def createLogger(logger, logLang):
    """
    Setting up logger
    """
    log_format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    file_handler = logging.FileHandler(filename=(os.path.join(OUT_DIR_LOGS, logLang + '-userdynamics.log')))
    file_handler.setFormatter(log_format)
    logger.setLevel(logging.INFO)
    logger.addHandler(file_handler)

这是一个大型的数据收集代码,为了避免在远程服务器上出现配额限制,我实现了以下的gzip和tar处理程序。

def gzipLogs(lang):
    """
    Compressing and tar
    """
    # Compressing logfiles and removing the old logfile
    original_filePath = OUT_DIR_LOGS + "/" +lang + "-userdynamics.log"
    gzip_filePath = OUT_DIR_LOGS + "/" + lang +"-userdynamics.gz"
    with open(original_filePath , 'rb') as original_file:
        with gzip.open(gzip_filePath, 'wb') as zipped_file:
            zipped_file.writelines(original_file)
    os.remove(original_filePath)
    # Compressing language folders that has data
    folder_path = OUT_DIR + "/" + lang
    tar_file = tarfile.open(folder_path + ".tgz", "w:gz")
    # add timestamp to arch file
    tar_file.add(folder_path, arcname = NOW + "_" + lang)
    tar_file.close()
    # delete the original file
    shutil.rmtree(folder_path)

我在一个嵌套的for循环中进行数据收集,并按照下面提到的方式调用日志记录器:

for something in somethings:
    for item in items:
        log = logging.getLogger()
        # Calling the logging configuration function.
        createLogger(log, lang)

一切运行得很好,但在执行后,删除.nsf文件时,仍然会留下残留文件,这导致配额问题依然存在。

所以我添加了以下代码段来关闭日志文件处理器,但这样做后我却遇到了以下错误:

关闭日志文件的代码:

unclosed_logs = list(log.handlers)
for uFile in unclosed_logs:
    print uFile
    log.removeHandler(uFile)
    uFile.flush()
    uFile.close()

上面的代码让我遇到了这个错误:

Traceback (most recent call last):
  File "/somefilepath/SomePythonFile.py", line 529, in <module>
    main()
  File "/somefilepath/SomePythonFile.py", line 521, in main
    gzipLogs(lang)
  File "/somefilepath/SomePythonFile.py", line 61, in gzipLogs
    with gzip.open(gzip_filePath, 'wb') as zipped_file:
AttributeError: GzipFile instance has no attribute '__exit__'

这是主方法的样子,里面包含了关闭处理器的代码段:

for something in somethings:
    for item in items:
        log = logging.getLogger()
        # Calling the logging configuration function.
        createLogger(log, lang)
    unclosed_logs = list(log.handlers)
    for uFile in unclosed_logs:
        print uFile
        log.removeHandler(uFile)
        uFile.flush()
        uFile.close()

我到底做错了什么?我是在错误地处理日志记录器吗?还是我关闭文件的时机太早了?

2 个回答

1

有几个问题可能会导致麻烦:

  1. 你应该只在程序的一个地方配置日志记录(比如设置级别、添加处理器),最好是在 if __name__ == '__main__' 这个部分。看起来你没有这样做。需要注意的是,你可以使用 WatchedFileHandler,并使用外部工具来轮换你的日志文件,比如 logrotate 提供了轮换和压缩的功能。
  2. 你提到的关于 __exit__ 的错误和日志记录没有关系,可能是和 Python 版本有关。GZipFile 只有在 Python 2.7 / 3.2 版本中才能和 with 一起使用,在更早的版本中,如果你尝试在 with 语句中使用 GZipFile,就会出现错误信息。
0

经过一些研究,我发现我执行文件的服务器使用的是Python 2.6,而在2.6版本中,GZip模块没有with open这个功能。要解决这个问题,要么把Python版本换成2.7,要么就用传统的方法,在一个try-catch块中打开文件。

try:
    inOriginalFile = open(original_filePath, 'rb')
    outGZipFile = gzip.open(gzip_filePath, 'wb')
    try:
        outGZipFile.writelines(inOriginalFile)
    finally:
        outGZipFile.close()
        inOriginalFile.close()
except IOError as e:
    logging.error("Unable to open gzip files, GZIP FAILURE")

这就是我解决这个问题的方法。

撰写回答