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

Python defer.DeferredSemaphore类代码示例

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

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



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

示例1: trigger_convergence_groups

def trigger_convergence_groups(authenticator, region, groups,
                               concurrency_limit, no_error_group):
    """
    Trigger convergence on given groups

    :param IAuthenticator authenticator: Otter authenticator
    :param str region: Region where this is running
    :param list groups: List of group dicts
    :param int concurrency_limit: Concurrency limit
    :param bool no_error_group: If true then do not converge ERROR groups

    :return: Deferred fired with None
    """
    sem = DeferredSemaphore(concurrency_limit)
    d = DeferredList(
        [sem.run(trigger_convergence, authenticator, region, group,
                 no_error_group)
         for group in groups],
        fireOnOneCallback=False,
        fireOnOneErrback=False,
        consumeErrors=True)
    d.addCallback(
        lambda results: [(g["tenantId"], g["groupId"], f.value)
                         for g, (s, f) in zip(groups, results) if not s])
    return d
开发者ID:meker12,项目名称:otter,代码行数:25,代码来源:trigger_convergence.py


示例2: recordVideoProcess

	def recordVideoProcess(self, resW, resH, totalTimeSec, framerate, serverIP, piName, recordTimesList, file):
		semi = DeferredSemaphore(1)

		jobs = []
		for runs in range(len(recordTimesList)/2):
			print  "recordTimes recordVideoProcess:", recordTimesList
			self.writeFile("recordTimes recordVideoProcess:")
			try:
				startAtTime = self.calculateTimeDifference(recordTimesList.pop(0), recordTimesList.pop(0))
				jobs.append(semi.run(tv.takeVideo, int(resW), int(resH), int(totalTimeSec),\
						int(framerate), startAtTime, serverIP, piName, file))
			except:
				self.writeFile("That time was not valid. Calling next time.")
				self.writeFile("len recordTimesList: " + str(len(recordTimesList)))
				if len(recordTimesList)%2>0:
					self.writeFile("odd number")
					recordTimesList.pop(0)
					self.writeFile("new len: " + str(len(recordTimesList)))
					reactor.callLater(0.5, self.transport.write, "TIMEINPUTERROR {0}\n".format(piName))
				continue
			
		jobs = DeferredList(jobs)

		print  "Results: ", jobs.addCallback(self.getResults, piName)
		# self.writeFile("Results: ", jobs.addCallback(self.getResults, piName))
		jobs.addCallback(lambda _: reactor.callLater(5, reactor.stop))
开发者ID:msit18,项目名称:UrbanFlows,代码行数:26,代码来源:testUploadSpeed4.py


示例3: ThreadedUrllib2TestMixin

class ThreadedUrllib2TestMixin(object):

    def setUp(self):
        self._semaphore = DeferredSemaphore(2)

    def tearDown(self):
        pass


    def getPages(self, count, url):
        return gatherResults([self.getPage(url) for i in xrange(0, count)])

    @inlineCallbacks
    def getPage(self, url):
        yield self._semaphore.acquire()
        page = yield deferToThread(self._openPage, url)
        self._semaphore.release()
        returnValue(page)

    def _openPage(self, url):
        log.msg("Opening url: %r" % url)
        return urlopen(url).read()

    @inlineCallbacks
    def getPageLength(self, url):
        response = yield self.getPage(url)
        returnValue(len(response))
开发者ID:alexstaytuned,项目名称:tx-pendrell,代码行数:27,代码来源:_test_comparison.py


示例4: __init__

 def __init__(self, buffer, start_callback=None):
     self.buffer = buffer
     self._done = False
     self._flush = DeferredSemaphore(1)
     self._waiter = DeferredSemaphore(1)
     self._flush.acquire()
     self._started = start_callback
     self._keepalive = LoopingCall(self._send_keepalive)
开发者ID:ahaas,项目名称:smap,代码行数:8,代码来源:plotly.py


示例5: parallel_map

def parallel_map(iterable, fn, *args, **kwargs):
    deferreds = []
    parallelism_limiter = DeferredSemaphore(MAX_PARALLELISM)
    for item in iterable:
        d = parallelism_limiter.run(fn, item, *args, **kwargs)
        deferreds.append(d)
    results = yield gatherResults(deferreds)
    returnValue(results)
开发者ID:dellis23,项目名称:rollingpin,代码行数:8,代码来源:utils.py


示例6: __init__

 def __init__(self, tokens = 5):
     if tokens < 1:
         raise ValueError("tokens must be > 0")
     
     if tokens == 1:
         self.lock = DeferredLock()
     else:
         self.lock = DeferredSemaphore(tokens)
开发者ID:e000,项目名称:prickle,代码行数:8,代码来源:util.py


示例7: trigger_convergence_groups

def trigger_convergence_groups(authenticator, region, groups,
                               concurrency_limit):
    """
    Trigger convergence on given groups
    """
    sem = DeferredSemaphore(concurrency_limit)
    return gatherResults(
        [sem.run(trigger_convergence, authenticator, region, group)
         for group in groups],
        consumeErrors=True)
开发者ID:glyph,项目名称:otter,代码行数:10,代码来源:trigger_convergence.py


示例8: __init__

 def __init__(self, mapsPath, fetchURL, deleteIfNotPresent, tfLevelSounds):
     assert isinstance(mapsPath, str) and len(mapsPath)
     assert isinstance(fetchURL, str) and len(fetchURL)
     self.mapsPath = FilePath(mapsPath)
     self.downloadTempPath = self.mapsPath.child('mapupdater')
     self.fetchURL = URLPath.fromString(fetchURL)
     self.deleteIfNotPresent = deleteIfNotPresent
     self.tfLevelSounds = tfLevelSounds
     self.semaphore = DeferredSemaphore(1)
     self.downloadSemaphore = DeferredSemaphore(4)
     for fp in self.downloadTempPath.globChildren('*.bsp.bz2'):
         fp.remove()
开发者ID:jsza,项目名称:tempus-map-updater,代码行数:12,代码来源:updater.py


示例9: runFiles

	def runFiles():
	    semi = DeferredSemaphore(1)

	    jobs = []
	    for runs in range(5):
	        jobs.append(semi.run(collectFiles))

	    jobs = DeferredList(jobs)
	    def cbFinished(ignored):
	        print 'Finishing job'
	    jobs.addCallback(cbFinished)
	    return jobs
开发者ID:msit18,项目名称:UrbanFlows,代码行数:12,代码来源:wholeProcess.py


示例10: Processor

class Processor():
    """
    Whenever mixtapeReceived is called, deferToThread is scheduled to be run as
    soon as a "slot" for being run is available. There is currently 1 slot
    deferToThread runs process_mixtape in another thread, and releases the
    slot when its that process is done
    """
    def __init__(self):
        self.sem = DeferredSemaphore(1) #do one thing at a time

    def mixtapeReceived(self, mixtape):
        debug("Adding %s to be processed" % mixtape)
        self.sem.run(deferToThread, process.process_mixtape, *mixtape)
开发者ID:brandonivey,项目名称:mixtapes,代码行数:13,代码来源:server.py


示例11: request

    def request(self, method, uri, headers=None, bodyProducer=None):
        """
        Issue a new request.
        @param method: The request method to send.
        @type method: C{str}
        @param uri: The request URI send.
        @type uri: C{str}
        @param scheme: A string like C{'http'} or C{'https'} (the only two
            supported values) to use to determine how to establish the
            connection.
 
        @param host: A C{str} giving the hostname which will be connected to in
            order to issue a request.

        @param port: An C{int} giving the port number the connection will be on.

        @param path: A C{str} giving the path portion of the request URL.
        @param headers: The request headers to send.  If no I{Host} header is
            included, one will be added based on the request URI.
        @type headers: L{Headers}
        @param bodyProducer: An object which will produce the request body or,
            if the request body is to be empty, L{None}.
        @type bodyProducer: L{IBodyProducer} provider
        @return: A L{Deferred} which fires with the result of the request (a
            L{Response} instance), or fails if there is a problem setting up a
            connection over which to issue the request.  It may also fail with
            L{SchemeNotSupported} if the scheme of the given URI is not
            supported.
        @rtype: L{Deferred}
        """
        scheme, host, port, path = _parse(uri)
        if headers is None:
            headers = Headers()
        if not headers.hasHeader('host'):
            # This is a lot of copying.  It might be nice if there were a bit
            # less.
            headers = Headers(dict(headers.getAllRawHeaders()))
            headers.addRawHeader(
                'host', self._computeHostValue(scheme, host, port))
        if self.persistent:
            sem = self._semaphores.get((scheme, host, port))
            if sem is None:
                sem = DeferredSemaphore(self.maxConnectionsPerHostName)
                self._semaphores[scheme, host, port] = sem
            return sem.run(self._request, method, scheme, host, port, path,
                           headers, bodyProducer)
        else:
            return self._request(
                method, scheme, host, port, path, headers, bodyProducer)
开发者ID:Hexadite-Omri,项目名称:txwinrm,代码行数:49,代码来源:_zenclient.py


示例12: collectFiles

	def collectFiles():
	    semaphore = DeferredSemaphore(1)
	    files = glob.glob('*.py')
	    dl = list()

	    for item in range(len(files)):
	        #Queues list of things to be sent and runs it
	        dl.append(semaphore.run(sendFiles, files[item]))

	    # convert to a DefferedList. Allows for callback call
	    dl = DeferredList(dl)
	    def cbFinished(ignored):
	        print 'Finishing job'
	    dl.addCallback(cbFinished)
	    return dl
开发者ID:msit18,项目名称:UrbanFlows,代码行数:15,代码来源:wholeProcess.py


示例13: main

def main():
    agent = Agent(reactor)
    sem = DeferredSemaphore(5)
    print "Loading IDs"
    ids = getBeermeIds()
    ids = ids[:100]
    print "Done Loading %s IDs" % str(len(ids))
    jobs = []
    for id in ids:
        jobs.append(sem.run(beerme_request,id,agent))
    d = gatherResults(jobs)
    d.addBoth(cbShutdown)

    print "Starting reactor..."
    reactor.run()
开发者ID:buckhx,项目名称:py-beer,代码行数:15,代码来源:beerme_crawler.py


示例14: __init__

    def __init__(self, conn_str):
        self.waiting = []
        self.inuse = []
        self.free = []

        self.semaphore = DeferredSemaphore(1)
        self.updateTime()
开发者ID:sociam,项目名称:indx,代码行数:7,代码来源:connectionpool.py


示例15: main

def main():
    agent = Agent(reactor)
    sem = DeferredSemaphore(10)
    print "Loading breweries..."
    mongo = MongoClient().entities.breweries
    breweries = loadBreweries(mongo)
    print "Done loading breweries."
    jobs = []
    for brewery in breweries:
        jobs.append(sem.run(socialRequest,brewery,agent,mongo))
    #    if len(jobs) % 50 == 0:
    #        print "Brewery Jobs started: %d" % len(jobs) 
    d = gatherResults(jobs)
    d.addBoth(cbShutdown)
    print "Let the Reactor BEGIN!"
    reactor.run()
开发者ID:buckhx,项目名称:py-beer,代码行数:16,代码来源:find_social.py


示例16: start

    def start(self):
        """ get each page """
        deferreds = []
        sem = DeferredSemaphore(self.MAX_RUN)
        
        for key in self.book.keys():

            sleep(self.RATE_LIMIT)
            d =  sem.run(getPage, self.book[key])
            d.addCallback(self.pageCallback, key)
            d.addErrback(self.errorHandler, key)
            deferreds.append(d)

        dl = DeferredList(deferreds)
        dl.addCallback(self.listCallback)
        dl.addCallback(self.finish)
开发者ID:rmcdonnell,项目名称:greenCall,代码行数:16,代码来源:crawlah.py


示例17: PlotlyStreamProducer

class PlotlyStreamProducer(object):
    """Implements a producer that copies from a buffer to a plot.ly
    connection.
    """
    implements(IBodyProducer)
    length = UNKNOWN_LENGTH

    def __init__(self, buffer, start_callback=None):
        self.buffer = buffer
        self._done = False
        self._flush = DeferredSemaphore(1)
        self._waiter = DeferredSemaphore(1)
        self._flush.acquire()
        self._started = start_callback
        self._keepalive = LoopingCall(self._send_keepalive)

    @inlineCallbacks
    def startProducing(self, consumer):
        self._keepalive.start(60)
        self._started.callback(None)
        while True:
            # if paused, this will block
            yield self._waiter.acquire()
            while len(self.buffer):
                v = self.buffer.pop(0)
                if v is not None:
                    consumer.write(json.dumps(v))
                consumer.write("\n")
            yield self._waiter.release()

            if self._done: 
                return
            yield self._flush.acquire()

    def pauseProducing(self):
        return self._waiter.acquire()

    def resumeProducing(self):
        return self._waiter.release()

    def stopProducing(self):
        self._done = True
        if self._keepalive.running:
            self._keepalive.stop()

    def _send_keepalive(self):
        self.buffer.append(None)
        self.flush()

    def flush(self):
        if self._flush.tokens == 0:
            self._flush.release()
开发者ID:ahaas,项目名称:smap,代码行数:52,代码来源:plotly.py


示例18: __init__

 def __init__(self, crawler, show_window=False, qt_platform="minimal",
              enable_webkit_dev_tools=False, page_limit=4,
              cookies_middleware=None):
     super(BaseQtWebKitMiddleware, self).__init__()
     self._crawler = crawler
     self.show_window = show_window
     self.qt_platform = qt_platform
     self.enable_webkit_dev_tools = enable_webkit_dev_tools
     if page_limit != 1:
         if QWebSettings is not None:
             QWebSettings.setObjectCacheCapacities(0, 0, 0)
     if page_limit is None:
         self.semaphore = DummySemaphore()
     else:
         self.semaphore = DeferredSemaphore(page_limit)
     self.cookies_middleware = cookies_middleware
     self._references = set()
开发者ID:ArturGaspar,项目名称:scrapy-qtwebkit,代码行数:17,代码来源:__init__.py


示例19: trigger_convergence_groups

def trigger_convergence_groups(authenticator, region, groups, concurrency_limit, no_error_group):
    """
    Trigger convergence on given groups

    :param IAuthenticator authenticator: Otter authenticator
    :param str region: Region where this is running
    :param list groups: List of group dicts
    :param int concurrency_limit: Concurrency limit
    :param bool no_error_group: If true then do not converge ERROR groups

    :return: Deferred fired with None
    """
    sem = DeferredSemaphore(concurrency_limit)
    return gatherResults(
        [sem.run(trigger_convergence, authenticator, region, group, no_error_group) for group in groups],
        consumeErrors=True,
    ).addCallback(lambda _: None)
开发者ID:stanzikratel,项目名称:otter,代码行数:17,代码来源:trigger_convergence.py


示例20: __init__

 def __init__(self, queue):
     self.managedPackageVersions = set()
     self.certifiDirectory = tempfile.mkdtemp()
     self.testSemaphore = DeferredSemaphore(tokens=32)
     self.binPath = os.path.join(
         os.path.split(__file__)[0], 'certifi_test.py'
     )
     self.queue = queue
     self._log = logger.new(object="supervisor")
开发者ID:Lukasa,项目名称:testifi,代码行数:9,代码来源:supervisor.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python endpoints.clientFromString函数代码示例发布时间:2022-05-27
下一篇:
Python defer.DeferredQueue类代码示例发布时间: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