【发布时间】:2017-10-24 20:11:34
【问题描述】:
我在这个网站上已经有一段时间了,我发现了很多有用的解决方案来解决我在构建我的第一个 python 程序时遇到的问题。我希望你们能再次帮助我。
我正在尝试启动数量不定的多进程,每个进程都使用一小部分列表进行扫描。我一直在修改队列,但是当我实现它们时,它们总是给我的循环增加大量时间。我希望最大限度地提高我的速度,同时保护我的 Titles.txt 免受错误内容的影响。让我告诉你我的代码。
l= ['url1', 'url2', etc]
def output(t):
f = open('Titles.txt','a')
f.write(t)
f.close()
def job(y,processload):
calender = ['Jan', 'Feb', 'Mar', 'Dec'] #the things i want to find
for i in range(processload): #looping processload times
source = urllib.request.urlopen(l[y]).read() #read url #y
soup = bs.BeautifulSoup(source,'lxml')
for t in soup.html.head.find_all('title'):
if any(word in t for word in calender):
output(t) #this what i need to queue
y+=1 #advance url by 1
if __name__ == '__main__':
processload=5 #the number of urls to be scanned by job
y=0 #the specific count of url in list
runcount = 0
while runcount == 0: #engage loop
for i in range(380/processload): #the list size / 5
p= multiprocessing.Process(target=job, args=(y,processload)
p.start()
y+=processload #jump y ahead
上面的代码允许在我的循环中实现最大速度。我想在保持速度的同时保护我的输出。我一直在搜索示例,但我还没有找到具有在子进程中启动的锁或队列的代码。你会建议我如何进行?
非常感谢。
【问题讨论】:
-
我假设您需要创建一个
Queue并将其作为元组中的另一个参数传递。然后每个进程可以将t推送到队列中。然后,当进程退出时(您将需要它们的集合并加入所有进程),您可以将队列处理为“Titles.txt” -
由于进程会无限循环,我是否需要在
for i in range之后在循环中运行写入? -
我不知道您所说的无休止回收是什么意思,但是您要么等待所有进程完成(在每个
Process上调用join())然后为队列服务,要么您也启动另一个Process将Queue下沉到文件中。 -
那么,为了等待进程完成,我需要
o=output(t),o.join()吗? -
不,看我的回答。
标签: python performance queue locking multiprocessing