用于网络任务的Python序列多线程

2024-04-19 19:08:24 发布

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

我正在尝试用多个线程运行脚本,以减少脚本完成所需的时间。 我需要知道如何在这样的程序中实现多线程

脚本示例:

def getnetworkdata():
   data = ["somesite.com/1", "somesite.com/2", "somesite.com/3", "somesite.com/4"]
   for url in data:
      r = requests.get(url)
      someOtherArray.append(r.text)

线程应该为所需的任务按顺序运行

我期望的输出:

someOtherArray = [1, 2, 3, 4]

我正在使用Python2.x


Tags: in程序脚本comurl示例fordata
1条回答
网友
1楼 · 发布于 2024-04-19 19:08:24
from multiprocessing.dummy import Pool as ThreadPool

data = ["somesite.com/1", "somesite.com/2", "somesite.com/3", "somesite.com/4"]

# Make the Pool of workers
pool = ThreadPool(4)

# Open the urls in their own threads
# and return the results
results = pool.map(requests.get, data)

someOtherArray = map( lambda x: x.text, results )

#close the pool and wait for the work to finish 
pool.close()
pool.join()

相关问题 更多 >