gpt4 book ai didi

python - 在 Python 中跟踪一个被忽略的异常?

转载 作者:太空狗 更新时间:2023-10-29 22:27:04 25 4
gpt4 key购买 nike

我的应用有一个自定义音频库,它本身使用 BASS 库。

我在整个程序中创建和销毁 BASS 流对象。

当我的程序随机退出时(我还没有弄清楚模式)我在我的控制台上收到以下通知:

Exception TypeError: "'NoneType' object is not callable" in <bound method stream.__del__ of <audio.audio_player.stream object at 0xaeda2f0>> ignored

我的音频库 (audio/audio_player.py [class Stream]) 包含一个创建 BASS 流对象然后允许代码操作它的类。当类被销毁时(在 del 例程中)它调用 BASS_StreamFree 来清除 BASS 可能分配的任何资源。

(audio_player.py)

from pybass import *
from ctypes import pointer, c_float, c_long, c_ulong, c_buffer
import os.path, time, threading

# initialize the BASS engine
BASS_Init(-1, 44100, 0, 0, None)

class stream(object):
"""Represents a single audio stream"""
def __init__(self, file):
# check for file existence
if (os.path.isfile(file) == False):
raise ValueError("File %s not found." % file)
# initialize a bass channel
self.cAddress = BASS_StreamCreateFile(False, file, 0, 0, 0)
def __del__(self):
BASS_StreamFree(self.cAddress)
def play(self):
BASS_ChannelPlay(self.cAddress, True)
while (self.playing == False):
pass
..more code..

基于此消息,我的第一个倾向是在我的代码中的某处,我的流类的一个实例被孤立(不再分配给一个变量)并且 Python 仍在尝试调用它的 del在应用程序关闭时运行,但在它尝试时对象已经消失。

此应用程序确实使用了 wxWidgets,因此涉及一些线程。事实上,我没有得到一个实际的变量名,这让我相信我在上一段中所说的话。

我不确定究竟是什么代码与调试相关。该消息看起来确实无害,但我不喜欢在最终生产代码中“忽略”异常的想法。

有没有人有调试这个的任何技巧?

最佳答案

异常被忽略的消息是因为在 __del__ 方法中引发的所有异常都被忽略以保持数据模型的完整性。这是 the docs 的相关部分:

Warning: Due to the precarious circumstances under which __del__() methods are invoked, exceptions that occur during their execution are ignored, and a warning is printed to sys.stderr instead. Also, when __del__() is invoked in response to a module being deleted (e.g., when execution of the program is done), other globals referenced by the __del__() method may already have been deleted or in the process of being torn down (e.g. the import machinery shutting down). For this reason, __del__() methods should do the absolute minimum needed to maintain external invariants. Starting with version 1.5, Python guarantees that globals whose name begins with a single underscore are deleted from their module before other globals are deleted; if no other references to such globals exist, this may help in assuring that imported modules are still available at the time when the __del__() method is called.

至于调试它,您可以先在 __del__ 方法中的代码周围放置一个 try/except block ,然后打印出更多有关程序在其发生时的状态的信息。或者您可以考虑在 __del__ 方法中做更少的事情,或者完全摆脱它!

关于python - 在 Python 中跟踪一个被忽略的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16620932/

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