• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python threadpool.ThreadPool类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中threadpool.ThreadPool的典型用法代码示例。如果您正苦于以下问题:Python ThreadPool类的具体用法?Python ThreadPool怎么用?Python ThreadPool使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了ThreadPool类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: run

    def run(self, env, json_writer):
        '''
        Schedule all tests in profile for execution.

        See ``Test.schedule`` and ``Test.run``.
        '''

        self.prepare_test_list(env)

        # If using concurrency, add all the concurrent tests to the pool and
        # execute that pool
        if env.concurrent:
            pool = ThreadPool(multiprocessing.cpu_count())
            for (path, test) in self.test_list.items():
                if test.runConcurrent:
                    pool.add(test.execute, (env, path, json_writer))
            pool.join()

        # Run any remaining tests serially from a single thread pool after the
        # concurrent tests have finished
        pool = ThreadPool(1)
        for (path, test) in self.test_list.items():
            if not env.concurrent or not test.runConcurrent:
                pool.add(test.execute, (env, path, json_writer))
        pool.join()
开发者ID:RAOF,项目名称:piglit,代码行数:25,代码来源:core.py


示例2: testImageDownload

 def testImageDownload(self):
     logging.debug('Start at %s', datetime.now())
     url = 'http://f1.163.com'
     # url = 'http://news.sina.com.cn/photo/'
     work_request = WorkRequest(spider, url)
     pool = ThreadPool(10, work_request)
     pool.poll()
开发者ID:steve-fan,项目名称:threadpool,代码行数:7,代码来源:test.py


示例3: convertFlv2Mp4underDir

def convertFlv2Mp4underDir(path):
    if not os.path.isdir(path):
        if os.path.exists(path):
            print "  Path:["+ path+ "] is not a directory, exit!\n"
            return
        else:
            os.makedirs(path)
    
    pool = ThreadPool(6)
    
    MP4_CMD = '''D:\\Program\\tools\\ffmpeg.exe -i "%s" -vcodec mpeg4 -b 1200kb -mbd 2 -aic 2 -cmp 2 -subcmp 2 -acodec libfaac -ac 2 -ab 128000 -y "%s"'''
    MP3_CMD = '''D:\\Program\\tools\\ffmpeg.exe -i "%s" -vn -ar 44100 -ac 2 -f mp3 "%s"'''
    for file_name in os.listdir(path):
        flv_path = path+'\\'+file_name
        if os.path.isfile(flv_path):
            mp4_file_name = file_name[:file_name.rfind('.')]+'.mp4'
            mp4_save_path = path+'\\mp4\\'+mp4_file_name
            if os.path.exists(mp4_save_path):
                print "  File:[" + mp4_save_path+ "] already exists, pass.\n"
            else:
                cmd = MP4_CMD%(flv_path, mp4_save_path)
                #print cmd
                #pool.queueTask(run_cmd, (cmd))
            
            mp3_file_name = file_name[:file_name.rfind('.')]+'.mp3'
            mp3_save_path = path+'\\mp3\\'+mp3_file_name
            if os.path.exists(mp3_save_path):
                print "  File:[" + mp3_save_path+ "] already exists, pass.\n"
            else:
                cmd = MP3_CMD%(flv_path, mp3_save_path)
                print cmd
                pool.queueTask(run_cmd, (cmd))
            
    pool.joinAll()
开发者ID:Letractively,项目名称:code-of-ldmiao,代码行数:34,代码来源:convert_flv.py


示例4: downloadAllPagesVideos

def downloadAllPagesVideos(url):
    global proxy, host, thread_count
    print url
    content = getContent(url, None, proxy)
    
    all_page_content = ''
    matched_groups = re.findall('''<a href="(.*?)" title='第\d+页' charset=".*?">\d+</a>''', content)
    for matched in matched_groups:
        page_url = 'http://so.youku.com'+matched.strip()
        all_page_content += getContent(page_url, None, proxy)
    
    
    pool = ThreadPool(thread_count)

    video_url_set = set()
    matched_groups = re.findall('''<a href="(http\://v\.youku\.com/v_show/id_.*?=\.html)"''', all_page_content)
    for matched in matched_groups:
        #print matched.strip()
        video_url = matched.strip()
        video_url_set.add(video_url)

    for video_url in video_url_set:
        print video_url
        log(video_url)
        pool.queueTask(downloadVideo, (video_url))

    pool.joinAll()
开发者ID:Letractively,项目名称:code-of-ldmiao,代码行数:27,代码来源:youku_downloader.py


示例5: __init__

class Spider:
	def __init__(self, depth=2):
		self.threadPool = ThreadPool(10)
		self.depth = depth

	def start(self, currentLevel, url):
		self.threadPool.initPool()
		self.threadPool.putTask(self.crawlPage, \
							currentLevel = currentLevel, \
							url = url)

	def crawlPage(self, args):
		print 'crawlPage', args
		currentLevel = args['currentLevel']
		url = args['url']
		req = urllib2.Request(url=url, headers=header)
		try:
			resp = urllib2.urlopen(req, timeout=10)
		except urllib2.HTTPError as e:
			# XXX The except HTTPError must come first
			# otherwise except URLError will also catch an HTTPError
			pass
		except urllib2.URLError as e:
			pass
		except Exception, e:
			print e
		else:
开发者ID:pansuo,项目名称:spider,代码行数:27,代码来源:spider.py


示例6: convertWMA2MP3underDir

def convertWMA2MP3underDir(path):
    if not os.path.isdir(path):
        if existFile(path):
            print "  Path:["+ path+ "] is not a directory, exit!\n"
            return
        else:
            os.makedirs(path)
    
    pool = ThreadPool(6)
    
    MP3_CMD = '''ffmpeg.exe -i "%s" -f mp3 "%s"'''
    DEL_CMD = '''del %s'''
    for file_name in os.listdir(path):
        wma_path = path+'\\'+file_name
        if os.path.isfile(wma_path) and wma_path.lower().endswith('.wma'):
            mp3_file_name = file_name[:file_name.rfind('.')]+'.mp3'
            mp3_save_path = path+'\\'+mp3_file_name
            if os.path.exists(mp3_save_path):
                print "  File:[" + mp3_save_path+ "] already exists, pass.\n"
            else:
                cmd1 = MP3_CMD%(wma_path, mp3_save_path)
                #cmd2 = DEL_CMD%(wma_path)
                print cmd1
                pool.queueTask(run_cmd, (cmd1))
        
    pool.joinAll()
开发者ID:Letractively,项目名称:code-of-ldmiao,代码行数:26,代码来源:convert_wma.py


示例7: search

def search(song, n, processes=config.search_processes, returnGen=False):
	'''
	Function searches song and returns n valid .mp3 links.
	@param song: Search string.
	@param n: Number of songs.
	@param processes: Number of processes to launch in the subprocessing pool.
	@param returnGen: If true, a generator of the links will be returned,
						and not the calculated list itself.
	'''
	sources_list = [x for x in config.search_sources_const if config.search_sources[x]]
	log.debug("Using sources: %s" % sources_list)
	
	# IMPROVE: better handeling of slicing.
	pool = ThreadPool(max_threads=min(processes, len(sources_list)), catch_returns=True, logger=log)
	args_list = []
	for source in sources_list:
		args_list.append([song, source, n/len(sources_list)])
	if n % len(sources_list):
		args_list[-1][2] += 1
	
	for args in args_list:
		pool(parse)(*args)
	
	gen = pool.iter()

	if returnGen:
		return gen
	return list(gen)
开发者ID:shaharbukra,项目名称:iQuality,代码行数:28,代码来源:LinksGrabber.py


示例8: BBQ

class BBQ(object): 

        def __init__(self,t=180,count=8):
		
                
            
            self.time = float(t)
            self.count = int(count)
            
            self.ThreadPool = ThreadPool(self.count)
        
        '''
    实际处理烧烤任务的函数
    '''
        def handle(self,task):
            
            time.sleep(self.time)#模拟烧烤时间
            try:
                task[0] = True
            except:
                pass
            return 
         
        '''
    添加一个烧烤任务
    task格式:[True/False],
    True代表处理完成
    False 代表等待处理
    '''
        def addTask(self,task):
        
            self.ThreadPool.addTask(self.handle,task)
开发者ID:yongbo,项目名称:simulate_time-,代码行数:32,代码来源:bbq.py


示例9: pickle_all_companies

def pickle_all_companies():
    tpool = ThreadPool(50)
    companies = Company.objects.all()
    for c in companies:
        tpool.add_task(pickle_company, c.symbol)
    tpool.wait_completion()

    return None
开发者ID:maxvitek,项目名称:coint_site,代码行数:8,代码来源:pairs.py


示例10: render_rap

    def render_rap(self, msg_id, words):
        # Make the length of words fit the melody
        notes = sum(1 for pitch, beats in self._melody if pitch != REST)
        diff = notes - len(words)
        if diff < 0:
            words = words[:diff]
        else:
            words = words + ['la'] * diff

        delay = 0
        offsets = {}
        word_index = 0
        word_count = len(words)
        word_delays = []
        word_paths = []

        pool = ThreadPool(min(word_count, self._thread_pool))

        for pitch, beats in self._melody:
            duration = beats * self._spb

            if pitch != REST:
                word = words[word_index]
                word_delays.append(delay)
                word_path = '/tmp/%s-%s.wav' % (msg_id, word_index)
                word_paths.append(word_path)
                ssml = '<s><prosody pitch="%sHz" range="x-low">%s</prosody></s>' \
                    % (pitch, word)
                def task(word_id, ssml, word_path):
                    offsets[word_id] = self._swift.tts_file(ssml, word_path)
                pool.queue_task(task, (word_index, ssml, word_path))
                word_index += 1

            delay += duration

            if word_index == word_count:
                # Break here, rather than inside the if statement above, so that
                # that delay is updated and equals the duration of the rap.
                break

        pool.join_all()

        if not word_index:
            # Didn't render any words!
            return

        # Mix the rap and the backing track
        mix_path = '/tmp/%s-mix.wav' % msg_id
        sox_args = [self.sox_path, '-M'] + word_paths \
            + [self._backing_sample, mix_path, 'delay'] \
            + [str(delay + offsets[i]) for i, delay in enumerate(word_delays)] \
            + ['remix',
                ','.join(str(channel) for channel in range(1, word_count + 2)),
                'norm']
        print(' '.join(sox_args))
        subprocess.check_call(sox_args)

        return mix_path
开发者ID:Man-UP,项目名称:text-to-spit,代码行数:58,代码来源:tts.py


示例11: startWork

 def startWork(self, work, argsList, resultCallback=None):
   try:
     requests = makeRequests(work, argsList, resultCallback, None)
     job = ThreadPool(self.threadNum)
     for req in requests:
       job.putRequest(req)
     job.wait()
   except:
     print sys.exc_info()
开发者ID:JunfeiYang,项目名称:Python_project,代码行数:9,代码来源:login.py


示例12: ConcurrentTestPool

class ConcurrentTestPool(Singleton):
    @synchronized_self
    def init(self):
        self.pool = ThreadPool(multiprocessing.cpu_count())

    @synchronized_self
    def put(self, callable_, args=None, kwds=None):
        self.pool.putRequest(WorkRequest(callable_, args=args, kwds=kwds))

    def join(self):
        self.pool.wait()
开发者ID:chrisforbes,项目名称:piglit,代码行数:11,代码来源:threads.py


示例13: bfTest

def bfTest():
    pool = ThreadPool(100)
    for j in range(100):
        alltime = []
        for i in range(bingfa):
            work = WorkRequest(threads, args=(int(random.random() * portnum) % portnum,))
            pool.putRequest(work)
            sleep((1.0 / bingfa) * random.random())
            # threading.Thread(target=threads, args=(i % portnum,)).start()
        pool.wait()
        printdata(alltime)
开发者ID:dabeike,项目名称:waf,代码行数:11,代码来源:test.py


示例14: prime_cache

    def prime_cache(self):
        """Ensures that the webpage cache is filled in the
        quickest time possible by making many requests in
        parallel"""

        print "Getting data for parts from suppliers' websites"
        pool = ThreadPool(NUM_THREADS)

        for srcode, pg in self.iteritems():
            print srcode
            pool.add_task(pg.get_price)

        pool.wait_completion()
开发者ID:samphippen,项目名称:tools,代码行数:13,代码来源:bom.py


示例15: parse_soundcloud_api2

def parse_soundcloud_api2(title):
	'''
	Function connects to soundcloud.com and returns the .mp3 links in it.
	
	API method 2: Parsing player's json data.
	'''
	links = search_soundcloud(title)
	
	pool = ThreadPool(max_threads=5, catch_returns=True, logger=log)
	for link in links:
		pool(get_soundcloud_dl_link)(link)
	
	return pool.iter()
开发者ID:shaharbukra,项目名称:iQuality,代码行数:13,代码来源:LinksGrabber.py


示例16: refresh_tunnels

def refresh_tunnels(args):
    tunnels = db.store.find(Tunnel)
    if tunnels:
        pool = ThreadPool(tunnels.count())
        for tunnel in tunnels:
            request = WorkRequest(tunnel.check_available)
            pool.putRequest(request)

        pool.wait()
        
    for tunnel in tunnels:
        host = db.store.get(Host, tunnel.hostid)
        record = AvailabilityRecord.register(host, tunnel, check=False)
        print record
开发者ID:ZachGoldberg,项目名称:Personal-Cluster-Manager,代码行数:14,代码来源:refresh_tunnels.py


示例17: same_ms

def same_ms(product_id):
	data = {'product_id': product_id, 'address_id': '72858'}
	url = 'http://payment.ohsame.com/order_create'
	
	time_s = time.time()
	pool = ThreadPool(20)
	reqs = makeRequests(same_ms_req, [((url, data), {}) for i in range(200)], same_ms_callback)
	[pool.putRequest(req) for req in reqs]
	pool.wait()
	time_e = time.time()

	print('秒杀商品:%s\n' % str(product_id))
	print('秒杀结果:%s\n' % rs_ms)
	print('秒杀耗时:%s\n' % (time_e-time_s))
开发者ID:litterzhang,项目名称:same,代码行数:14,代码来源:same.py


示例18: aggregate_all

def aggregate_all(client, iterator, connection_factory):
    """
    Aggregate all feeds returned by the generator.

    The generator should contain pairs of two elements (feed_url, categories)
    """

    def attach_connection(thread):
        thread.hbase = connection_factory()
        return thread

    pool = ThreadPool(10, thread_init=attach_connection)
    for feed, categs in iterator:
        pool.queueTask(lambda worker, p: aggregate(worker.hbase, *p), (feed, categs))
    pool.joinAll()
开发者ID:hcmey,项目名称:feedaggregator,代码行数:15,代码来源:feeds.py


示例19: getSongsFromHTML

def getSongsFromHTML(htmlcontent, save_path):
    global thread_count

    pool = ThreadPool(thread_count)

    matched_groups = re.findall("""W[LS]\("(\d+)",\s*"(\d+)",\s*"(.*?)\s+",""", htmlcontent)
    for matched in matched_groups:
        print "-" * 2, matched
        order = matched[0].strip()
        song_id = matched[1].strip()
        song_name = matched[2].strip()
        # getSong(song_id, order, save_path)
        pool.queueTask(getSongThread, (song_id, order, save_path))

    pool.joinAll()
开发者ID:Letractively,项目名称:code-of-ldmiao,代码行数:15,代码来源:songtaste.py


示例20: start_thread

 def start_thread(self):
     args_list = []
     ips = self.parse_ip()
     for ip in ips:
         args = self.args.copy()
         args['ip'] = ip
         args_list.append(args)
     self.cui.w('Proxy Scanner started')
     self.cui.i('Nums: %s' % len(args_list))
     self.cui.i('Port: %s' % self.args['port'])
     self.cui.i('Thread: %s' % self.args['thread'])
     pool = ThreadPool(self.args['thread'])
     reqs = makeRequests(self.run, args_list)
     [pool.putRequest(req) for req in reqs]
     pool.wait()
开发者ID:green23,项目名称:ProxyValidator,代码行数:15,代码来源:ProxyValidator.py



注:本文中的threadpool.ThreadPool类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python PostFilterObject.PostFilterObject类代码示例发布时间:2022-05-27
下一篇:
Python threadpool.makeRequests函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap