gpt4 book ai didi

python - 如何找出哪一行代码使文件保持打开状态?

转载 作者:太空宇宙 更新时间:2023-11-04 10:47:10 25 4
gpt4 key购买 nike

我最近在我的服务器上收到关于“打开的文件太多”的异常。我检查了 lsof,果然,有一堆 PDF 文件保持打开状态(都在同一个目录中)。这个特定文件是通过 Django FileField 管理的。我试图追踪我的项目中任何按名称明确打开文件的地方,但我只能找到一个地方,据我所知,文件在那里被正确关闭。文件可能在其他地方保持打开状态,但我不知道如何找出实际上是什么代码使文件保持打开状态。我试过简单地搜索 open() 和 file() 的调用,但没有成功。

有什么方法可以系统地追踪哪一行代码导致文件打开?

编辑:我了解如何正确打开/关闭文件。我的问题是是否有一种方法可以追踪现有的代码行,该代码行使文件处于打开状态。

最佳答案

当您使用open 时,请尝试将其用作上下文管理器。这样,无论发生什么,它都会在您完成后关闭:

with open('file.txt', 'r') as fin:
# Access fin like normal

# No matter what happens, after the block, it's closed!

或者,您可以将 openclose 的实例替换为您自己的函数,为您执行一些额外的日志记录:

def my_open(filename, *args):
logger.debug('Opening %s' % filename)
return open(filename, *args)

def my_close(file_obj):
logger.debug('Closing %s' % file_obj.name)
return file_obj.close()

作为最后的手段,如果您无法访问有问题的代码,或者更改它会很麻烦,您可以尝试对函数进行猴子修补。

import traceback
class MyFile(file):
@staticmethod
def open(*args, **kwargs):
return MyFile(*args, **kwargs)

def __init__(self, *args, **kwargs):
self._file = self._open(*args, **kwargs)
print('Opening %s from %s' % (
self._file.name, ''.join(traceback.format_stack())))

def close(self):
print('Closing file %s from %s' % (
self._file.name, ''.join(traceback.format_stack())))
self._file.close()

# Now the monkey-patching
file = MyFile
MyFile._open = open
open = MyFile.open

o = open('hello', 'w+')

这当然不是世界上最漂亮的东西,但如果您能够对其进行猴子修补,那么您至少能够处理遗留代码。

关于python - 如何找出哪一行代码使文件保持打开状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16487863/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com