我有以下问题。我想实现一个Web攻击器,到目前为止,这很慢,但是我试图使用多处理来获取URL。不幸的是,我在这个领域不是很有经验。在阅读一些最简单的方法之后,我似乎是使用multiprocessing.pool
的map
方法为此。
但我不断收到以下错误:
TypeError: Pickling an AuthenticationString object is disallowed for security reasons
我发现很少有同样错误的案例,但不幸的是没有帮助我。
我创建了我的代码的剥离版本,该版本可以重现错误:
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()
我会非常感谢任何帮助或建议!
问题:但是我不断收到以下错误:
您遇到的错误是误导,原因是
self.queue = self.m.Queue()
将Queue
的实例化在class TestCrawler
之外。
这导致另一个错误:
notimplemplededError:池对象不能在进程或腌制之间传递
原因是:
self.pool = multiprocessing.Pool(6)
两个错误都表明pickle
找不到class Members
。
注意:无尽的循环!
您以下while
循环会导致无尽的循环! 这将 OVERLOAC 您的系统!
此外,您的pool.map(...
仅启动一个Process
with 一个 task> task!while True: self.pool.map(self.process_next_url, (self.queue,))
我建议阅读证明使用池的示例
更改为以下内容:
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()
此示例启动了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()
用Python测试:3.4.2