【问题标题】:Discord python bot: AttributeError: Can't pickle local objectDiscord python bot:AttributeError:无法腌制本地对象
【发布时间】:2018-05-27 09:47:27
【问题描述】:

您好,我正在尝试使用主类对我的 discord 机器人进行多处理,该类创建工作人员并检索不和谐消息以将它们放入队列中。当我初始化我的工人时,我将我的不和谐客户端作为参数传递,这是错误。

AttributeError: Can't pickle local object 'WeakSet.__init__.<locals>._remove'

我的代码:

class Master:
    def __init__(self):
        # Vars init
        print('Starting Master...')
        self.client = discord.Client()
        self.manager = Manager()
        self.user_spam = self.manager.dict()
        self.user_mute_chat = self.manager.dict()
        self.forbidden_words_list = []
        self.spam_t = self.manager.Value('i', 0)
        self.user_t_spam_muted = self.manager.Value('i', 0)
        self.to_master = []
        self.request_queue = Queue()
        self.cpu = cpu_count()

        # Web socket handlers
        # self.client.event(self.on_member_update)
        self.client.event(self.on_ready)
        self.client.event(self.on_message)

        # Bot init
        self.forbidden_words_list = self.manager.list(get_file_content('res/forbidden_words.txt'))
        for line in get_file_content('res/settings.txt'):
            if 'spamtime=' in line:
                self.spam_t = int(line.replace('spamtime=', ''))
            if 'usertimemuted' in line:
                self.user_t_spam_muted = int(line.replace('usertimemuted=', ''))

        # Workers init
        print('Starting Workers...')
        for i in range(self.cpu):
            Worker(self.request_queue, self.client, self.user_spam, self.user_mute_chat, self.spam_t,
                   self.user_t_spam_muted, self.forbidden_words_list).start()

        # Discord init
        print('Connecting to discord...')
        self.client.run(TOKEN)

class Worker(Process):
    def __init__(self, queue, client, user_spam, user_mute_chat, spam_t, user_t_spam_muted, forbidden_words_list):
        super(Worker, self).__init__()
        # Vars init
        self.client = client
        self.message = ''
        self.message_id = discord.Message
        self.word_list = []
        self.username = discord.Member
        self.queue = queue
        self.user_spam = user_spam
        self.user_mute_chat = user_mute_chat
        self.spam_t = spam_t
        self.user_t_spam_muted = user_t_spam_muted
        self.forbidden_words_list = forbidden_words_list

    async def run(self):
        # do some initialization here

        # Work here
        for data in iter(self.queue.get, None):
            pass

完整的追溯:

Traceback (most recent call last):
  File "C:/Users/PC/PycharmProjects/AIDiscord/AIDiscord.py", line 406, in <module>
    master = Master()
  File "C:/Users/PC/PycharmProjects/AIDiscord/AIDiscord.py", line 42, in __init__
    self.user_t_spam_muted, self.forbidden_words_list).start()
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36-32\Lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36-32\Lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36-32\Lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36-32\Lib\multiprocessing\popen_spawn_win32.py", line 65, in __init__
    reduction.dump(process_obj, to_child)
  File "C:\Users\PC\AppData\Local\Programs\Python\Python36-32\Lib\multiprocessing\reduction.py", line 60, in dump
    ForkingPickler(file, protocol).dump(obj)
AttributeError: Can't pickle local object 'WeakSet.__init__.<locals>._remove'
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0EDDAED0>

我搜索了一点,它在我 start() 进程时附加,它不依赖于我传递的参数。

【问题讨论】:

  • 显示完整的回溯。
  • 添加完整的回溯
  • 有一些讨论 here 看起来很相关,但我并不真正了解自己发生了什么。您可能遇到了错误,但由于问题已关闭,因此似乎没有。异步对象似乎是一个问题。如果从def run 中删除async 会怎样?
  • 我无法删除异步,我的方法:filter_chat_words() 和 spam_detection() 使用了 discord.py 的异步原因我尝试删除它,但仍然出现相同的错误
  • 我已经解决了大约 6 个小时的问题,但没有得到任何解决方案...

标签: python class pickle attributeerror discord.py


【解决方案1】:

您需要在 multiprocessing.Process.run 而不是 init 中创建 asyncio 循环和相关项目的实例。

我使用的模式是这样的:

import asyncio
import multiprocessing
import typing


class Process(multiprocessing.Process):

    def __init__(self,
                 group=None,
                 target=None,
                 name=None,
                 args=(),
                 kwargs=None):
        super().__init__(group, target, name, args, kwargs)
        self.loop: typing.Optional[asyncio.AbstractEventLoop] = None
        self.stopped: typing.Optional[asyncio.Event] = None

    def run(self):
        self.loop = asyncio.get_event_loop()
        self.stopped = asyncio.Event()
        self.loop.run_until_complete(self._run())
    
    async def _run(self):
        """My async stuff here"""

【讨论】:

    【解决方案2】:

    多处理库尝试腌制必要的对象。但是,您使用的是 Asyncio(“worker”类中的“run”方法),它会导致此错误。

    您不能在 Python 中腌制 Asyncio 对象。

    【讨论】:

      猜你喜欢
      • 2022-11-16
      • 2020-09-22
      • 2022-01-02
      • 1970-01-01
      • 2020-04-07
      • 2021-12-22
      • 2022-01-22
      • 2023-03-23
      • 2021-11-10
      相关资源
      最近更新 更多