Python 多处理-类型错误:出于安全原因,不允许对 AuthenticationString 对象进行酸洗

blu*_*nox 2 python queue multiprocessing python-3.x python-multiprocessing

我遇到以下问题。我想实现一个网络爬虫,到目前为止,它可以工作,但速度太慢,所以我尝试使用多重处理来获取 URL。不幸的是我在这个领域不是很有经验。经过一番阅读后,我认为最简单的方法是使用map来自的方法multiprocessing.pool

但我不断收到以下错误:

TypeError: Pickling an AuthenticationString object is disallowed for security reasons
Run Code Online (Sandbox Code Playgroud)

我发现很少有同样错误的案例,不幸的是它们并没有帮助我。

我创建了代码的精简版本,它可以重现该错误:

import multiprocessing

class TestCrawler:
    def __init__(self):
        self.m = multiprocessing.Manager()
        self.queue = self.m.Queue()
        for i in range(50):
            self.queue.put(str(i))
        self.pool = multiprocessing.Pool(6)



    def mainloop(self):
        self.process_next_url(self.queue)

        while True:
            self.pool.map(self.process_next_url, (self.queue,))                

    def process_next_url(self, queue):
        url = queue.get()
        print(url)


c = TestCrawler()
c.mainloop()
Run Code Online (Sandbox Code Playgroud)

我将非常感谢任何帮助或建议!

sto*_*vfl 5

问题:但我不断收到以下错误:

您收到的错误具有误导性,原因是

self.queue = self.m.Queue()
Run Code Online (Sandbox Code Playgroud)

将实例化移到Queue外部class TestCrawler移到.
这会导致另一个错误:

NotImplementedError:池对象无法在进程之间传递或腌制

原因是:

self.pool = multiprocessing.Pool(6)
Run Code Online (Sandbox Code Playgroud)

这两个错误都表明pickle找不到class Members.

注意:无限循环!
您的以下while循环将导致无限循环!这将使您的系统超载!
此外,您只能从一项pool.map(...任务开始一项Process

    while True:
        self.pool.map(self.process_next_url, (self.queue,)) 
Run Code Online (Sandbox Code Playgroud)

我建议阅读演示池使用的示例


更改为以下内容:

class TestCrawler:
    def __init__(self, tasks):
        # Assign the Global task to class member
        self.queue = tasks
        for i in range(50):
            self.queue.put(str(i))

    def mainloop(self):
        # Instantiate the pool local
        pool = mp.Pool(6)
        for n in range(50):
            # .map requires a Parameter pass None
            pool.map(self.process_next_url, (None,))

    # None is passed
    def process_next_url(self, dummy):
        url = self.queue.get()
        print(url)

if __name__ == "__main__":
  # Create the Queue as Global
  tasks = mp.Manager().Queue()
  # Pass the Queue to your class TestCrawler
  c = TestCrawler(tasks)
  c.mainloop()
Run Code Online (Sandbox Code Playgroud)

此示例启动 5 个进程,每个进程处理 10 个任务(url):

class TestCrawler2:
    def __init__(self, tasks):
        self.tasks = tasks

    def start(self):
        pool = mp.Pool(5)
        pool.map(self.process_url, self.tasks)

    def process_url(self, url):
        print('self.process_url({})'.format(url))

if __name__ == "__main__":
    tasks = ['url{}'.format(n) for n in range(50)]
    TestCrawler2(tasks).start()
Run Code Online (Sandbox Code Playgroud)

使用Python测试:3.4.2