Skip to main content
 首页 » 编程设计

Python:文件处理程序问题:删除文件而不留下 .nsf 文件

2025年05月04日9zhujiabin

我有以下方法来处理我的 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__' 

这是带有处理程序关闭代码段的 main 方法的样子:

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() 

我做错了什么?我处理记录器错误吗?还是我关闭文件太早了?

请您参考如下方法:

有很多事情可能会导致问题:

  1. 您应该只在程序的一个地方配置日志记录(例如设置级别、添加处理程序),最好是从 if __name__ == '__main__' 子句开始。你似乎没有这样做。请注意,您可以使用 WatchedFileHandler 并使用外部旋转器来旋转您的日志文件 - 例如logrotate提供旋转和压缩功能。
  2. 您与 __exit__ 相关的错误与日志记录无关 - 它可能与 Python 版本问题有关。 GZipFile 仅在 Python 2.7/3.2 中与 with 一起使用 - 在旧版本中,如果您尝试使用 GZipFile,您将收到错误消息在 with 语句中。