类析构函数中出现异常

问题描述 投票:0回答:1

执行代码时出现

ImportError
异常:

from requests import Session


class web_client(object):
    def __init__(self, adapter: type):
        self.adapter = adapter
        self.s = Session()
        self.s.verify = False
        self.adapter.auth(self)

    def __del__(self):
        self.adapter.close()
        self.s.close()

class adapter(object):

    @classmethod
    def process(cls):
        cls.client.s.get('https://stackoverflow.com')

    @classmethod
    def auth(cls, client: web_client):
        cls.client = client
        cls.process()

    @classmethod
    def close(cls):
        cls.process() # exception here


if __name__ == "__main__":
    web_client(adapter)

为什么这段代码会抛出错误以及如何避免它?

Exception ignored in: <function web_client.__del__ at 0x00000231EE1D8310>
Traceback (most recent call last):
 File "C:\Users\me\Desktop\main.py", line 12, in __del__
 File "C:\Users\me\Desktop\main.py", line 28, in close
 File "C:\Users\me\Desktop\main.py", line 19, in process
 File "C:\Anaconda3\lib\site-packages\requests\sessions.py", line 555, in get
 File "C:\Anaconda3\lib\site-packages\requests\sessions.py", line 528, in request
 File "C:\Anaconda3\lib\site-packages\requests\sessions.py", line 448, in prepare_request
 File "C:\Anaconda3\lib\site-packages\requests\cookies.py", line 544, in merge_cookies
 File "C:\Anaconda3\lib\site-packages\requests\cookies.py", line 352, in update
 File "C:\Anaconda3\lib\copy.py", line 92, in copy
ImportError: sys.meta_path is None, Python is likely shutting down
python python-3.x
1个回答
0
投票

找到了这个解决方案:

from requests import Session
from atexit import register


class web_client(object):
    def __init__(self, adapter: type):
        self.s = Session()
        self.s.verify = False
        register(adapter.close) # here is magic
        adapter.auth(self)

    def __del__(self):
        self.s.close()
        del self.s


class adapter(type):

    @classmethod
    def process(cls):
        cls.client.s.get('https://stackoverflow.com')

    @classmethod
    def auth(cls, client: web_client):
        cls.client = client
        cls.process()

    @classmethod
    def close(cls):
        cls.process()


if __name__ == "__main__":
    web_client(adapter)
© www.soinside.com 2019 - 2024. All rights reserved.