Python:无法启动新线程。我可以错开或延迟一些线程吗?

2024-04-26 13:37:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我还不太清楚该怎么问这个问题,因为我才刚刚开始学习python,但是这里是:

我有一个网络刮刀,它使用线程来获取信息。我正在寻找大约900种产品的定价和库存。当我用其中一半来测试脚本时,没有问题。当我试图报废所有900个产品时,我得到一个不能启动新线程错误。在

我想这是对内存的限制,或者是因为我向服务器请求的请求太多了

我想知道是否有一种方法可以减慢线程或错开请求。在

错误代码:

Traceback (most recent call last):
  File "C:\Python27\tests\dxpriceupdates.py", line 78, in <module>
    t.start()
error: can't start new thread
>>> 
Traceback (most recent call last):Exception in thread Thread-554:
Traceback (most recent call last):
  File "C:\Python27\lib\urllib.py", line 346, in open_http
    errcode, errmsg, headers = h.getreply()
  File "C:\Python27\lib\httplib.py", line 1117, in getreply
    response = self._conn.getresponse()
  File "C:\Python27\lib\httplib.py", line 1045, in getresponse
    response.begin()
  File "C:\Python27\lib\httplib.py", line 441, in begin
    self.msg = HTTPMessage(self.fp, 0)
  File "C:\Python27\lib\mimetools.py", line 25, in __init__
    rfc822.Message.__init__(self, fp, seekable)
  File "C:\Python27\lib\rfc822.py", line 108, in __init__
    self.readheaders()
  File "C:\Python27\lib\httplib.py", line 308, in readheaders
    self.addheader(headerseen, line[len(headerseen)+1:].strip())
MemoryError

<bound method Thread.__bootstrap of <Thread(Thread-221, stopped 9512)>>Traceback (most recent call last):
Traceback (most recent call last):
Traceback (most recent call last):

Traceback (most recent call last):
Unhandled exception in thread started by Unhandled exception in thread started by ...

这是Pythonskulist.txt只是一个文本文件,如12345、23445、5551……):

^{pr2}$

Tags: inpyselfmostliblinecallthread
1条回答
网友
1楼 · 发布于 2024-04-26 13:37:57

不要同时启动900个线程,你的电脑可能会窒息!相反,使用一个池并将活动分配给一定数量的工人。像这样使用multiprocessing

from multiprocessing import Pool

WORKERS = 10
p = Pool(WORKERS)
p.map(tr, skulist)

通过试验找到WORKERS的正确值。在

相关问题 更多 >