gpt4 book ai didi

python - 多线程 urllib2 在 Nose 框架上卡住

转载 作者:太空宇宙 更新时间:2023-11-03 18:03:25 25 4
gpt4 key购买 nike

我有一个使用nose_parameterized的Python代码,如下所示:

from nose_parameterized import parameterized
from multiprocessing.pool import ThreadPool
import urllib2

def make_http_call(url, req_type):
opener = urllib2.build_opener() # <=== this line causes it to freeze
return 1

pool = ThreadPool(processes=4)
results = []
urls = ['a', 'b', 'c', 'd']
for url in urls:
results.append(pool.apply_async(make_http_call, (url, 'html')))
d = {'add': []}
for ind, res in enumerate(results):
d['add'].append((res.get(), 2+ind, 3+ind))

@parameterized(d['add'])
def test_add(a, b, c):
assert a+b == c

这是代码的虚拟版本。基本上,我需要使用 http 请求响应加载测试参数,并且由于有很多 url,我想对它们进行多线程处理。一旦我添加 urllib2.build_opener,它就会使用 Nose 卡住(但在 python 中仍然可以正常工作)另外,我尝试过 urllib2.urlopen;一样的问题。有什么想法是否有“适当”(可调试)的方法来解决这个问题?

最佳答案

你可以用 Nose multiprocess为此内置插件,例如:

from nose_parameterized import parameterized
import urllib2

urls = ['http://www.google.com', 'http://www.yahoo.com']

@parameterized(urls)
def test_add(url):
a = urllib2.urlopen(url).read()

b = 2 + urls.index(url)
c = 3 + urls.index(url)
assert a+str(b) == str(c)

并使用nosetests --processes=2运行它。这使您能够将测试运行分布在一组工作进程中,这些进程按照您的预期并行运行测试。在幕后,使用了多处理模块。

关于python - 多线程 urllib2 在 Nose 框架上卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27324349/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com