- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在移植 library到 Python3。弹出的问题之一是所有 "unclosed file" warnings运行测试套件时。我已经解决了 95% 的警告,但还有一些警告仍然存在,我正在努力寻找代码中打开文件的位置。
有什么方法可以让 Python 在打开文件时记录堆栈帧,并在出现警告时显示堆栈帧?
我会对 stdlib 代码的猴子补丁感到满意,因为我只会将其用于一次性调试。
最佳答案
早在 2013 年就有一篇关于此的 python-dev 帖子,this post可能会帮助你。特别是,使用 tracemalloc 完成了一些猴子修补。
https://bitbucket.org/haypo/misc/src/tip/python/res_warn.py
"""
Tool to get the origin of ResourceWarning warnings on files and sockets.
Run python with -Wd to display warnings and call enable().
Use the new tracemalloc added in Python 3.4 beta 1.
Limitation: it does not work for text files, only for binary files. See:
http://bugs.python.org/issue19829
--
FileIO constructor calls ResourceWarning with the text representation of the
file, so ResourceWarning constructor does not have access to the file object.
Replacing ResourceWarning class in __builtins__ does not work because io.FileIO
destructor has an hardcoded reference to ResourceWarning.
Replacing io.FileIO doesn't work neither because io.open has an hardcoded
reference to io.FileIO.
Replacing warnings.showwarning to inspect the frame of the caller does not
work because the FileIO destructor is called when the last reference to the
file is set to None. So there is no more reference to the file.
"""
from io import FileIO as _FileIO
from socket import socket as _socket
import _pyio
import builtins
import linecache
import socket
import sys
import traceback
import tracemalloc
import warnings
def warn_unclosed(obj, delta=1):
delta += 1
tb = tracemalloc.get_object_traceback(obj)
if tb is None:
return
try:
warnings.warn("unclosed %r" % obj, ResourceWarning, delta + 1)
print("Allocation traceback (most recent first):")
for frame in tb:
print(" File %r, line %s" % (frame.filename, frame.lineno))
line = linecache.getline(frame.filename, frame.lineno)
line = line.strip()
if line:
print(" %s" % line)
if 0:
frame = sys._getframe(delta)
tb = traceback.format_stack(frame)
print("Destroy traceback (most recent last):")
for line in tb:
sys.stdout.write(line)
sys.stdout.flush()
finally:
obj.close()
class MyFileIO(_FileIO):
if 0:
def __init__(self, *args, **kw):
_FileIO.__init__(self, *args, **kw)
tb = tracemalloc.get_object_traceback(self)
if tb is None:
raise RuntimeError("tracemalloc is disabled")
def __del__(self):
if not self.closed:
warn_unclosed(self)
if hasattr(_FileIO, '__del__'):
_FileIO.__del__(self)
class MySocket(_socket):
if 0:
def __init__(self, *args, **kw):
_socket.__init__(self, *args, **kw)
tb = tracemalloc.get_object_traceback(self)
if tb is None:
raise RuntimeError("tracemalloc is disabled")
def __del__(self):
if not self._closed:
warn_unclosed(self)
if hasattr(_socket, '__del__'):
_socket.__del__(self)
def patch_open():
# Already patched
if _pyio.FileIO is MyFileIO:
return
# _io.open() uses an hardcoded reference to _io.FileIO
# use _pyio.open() which lookup for FilIO in _pyio namespace
_pyio.FileIO = MyFileIO
builtins.open = _pyio.open
def patch_socket():
socket.socket = MySocket
def enable(nframe=25):
if not tracemalloc.is_tracing():
tracemalloc.start(nframe)
patch_open()
patch_socket()
def main():
tracemalloc.start(25)
print("=== test unbuferred file ===")
patch_open()
f = open(__file__, "rb", 0)
f = None
print()
print("=== test socket ===")
patch_socket()
s = socket.socket()
s = None
print()
if __name__ == "__main__":
main()
关于python - 记录文件打开调试的位置 "ResourceWarning: unclosed file",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29926003/
if(1
if(1
public class Constants { public enum Status{ sen(3,"发送中"), suc(8,"成功"),
我需要匹配以下日期模式: dd-mmm-yyyy (TBC) dd-mmm-yyyy (TBD) dd-mmm-yyyy 但我收到以下异常,但我不明白错误是什么。我非常确定日期部分,我怀疑错误来源是
我正在尝试运行 sql 命令: SELECT *FROM wp_options WHERE option_name = 'active_plugins'; 但是我只收到一个错误,指出有一个未闭合的引号
我有一个用 Python 编写的 Reddit 机器人,有时我会收到以下错误: sys:1: ResourceWarning: unclosed ssl.SSLSocket fd=4, family=
我正在尝试实现此正则表达式来验证电子邮件: ([-!#-'*+/-9=?A-Z^-~]+(\.[-!#-'*+/-9=?A-Z^-~]+)* |"([]!#-[^-~\t]|(\\[\t -~]))+
将模板从 Java 转换为 Scala 时,我注意到以下带有多行注释的怪癖可以简化为以下代码段: /** * /* */ class Blah {} 上面的代码无法编译并显示“错误:未关闭的注释”
以下抛出异常: Pattern.matches(""+input.charAt(i),"\\s"); java.util.regex.PatternSyntaxException: Unclosed
我正在使用在 How to validate an email 找到的电子邮件验证模式它工作正常,除了它允许在电子邮件的第一部分使用 + 而这在我的规范中是不允许的。原代码为 public stati
查询 SELECT * FROM user WHERE username = 'Omnion' AND disable_flag = '0' 此查询在本地主机上运行良好, 上传到服务器后出现问题 Er
我的问题很简单:如果 html 内容中有像这个 img 标签这样的标签,有没有办法将 java 中的 html 解析为 DOM 文档? 这是在解析这些元素时给我一个 SAXException 的代码
我的代码如下: import asyncio import aiohttp urls = [ 'http://www.163.com/', 'http://www.sina.com.c
我正在移植 library到 Python3。弹出的问题之一是所有 "unclosed file" warnings运行测试套件时。我已经解决了 95% 的警告,但还有一些警告仍然存在,我正在努力寻找
最近,我在 Visual Studio 代码上编写 React 应用程序时遇到了问题。由于这个问题,每当我在 React 组件的渲染函数中编写 JSX 并保存它时,它就会变得困惑(我的意思是缩进会变得
在学习网络容器类(class)时Network Containers Lesson我遇到了一个错误 Template parsing error: template: :1: unclosed act
当我使用 ant 编译 Web 应用程序时,我收到以下编译器消息: unclosed character literal 有问题的代码行是: protected char[] diacriticVow
我正在尝试用 java 编写 emailValidator 函数,但遇到问题: public static boolean EmailValidator(String mail) { Patt
我使用 Hive SQL 使用 spark 执行此查询: var hiveContext = new org.apache.spark.sql.hive.HiveContext(sc) result
我正在开发 cv 并使用了 Realm 数据库,但出现以下错误 public class KitabSawti extends RealmObject { ^ warning: Unclosed fi
我是一名优秀的程序员,十分优秀!