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

Python threading.Event类代码示例

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

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



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

示例1: request_token_spotty

def request_token_spotty(spotty, use_creds=True):
    '''request token by using the spotty binary'''
    token_info = None
    if spotty.playback_supported:
        try:
            args = ["-t", "--client-id", CLIENTID, "--scope", ",".join(SCOPE), "-n", "temp-spotty"]
            done = Event()
            spotty = spotty.run_spotty(arguments=args, use_creds=use_creds)
            watcher = Thread(target=kill_on_timeout, args=(done, 5, spotty))
            watcher.daemon = True
            watcher.start()
            stdout, stderr = spotty.communicate()
            done.set()
            result = None
            log_msg("request_token_spotty stdout: %s" % stdout)
            for line in stdout.split():
                line = line.strip()
                if line.startswith("{\"accessToken\""):
                    result = json.loads(line)
            # transform token info to spotipy compatible format
            if result:
                token_info = {}
                token_info["access_token"] = result["accessToken"]
                token_info["expires_in"] = result["expiresIn"]
                token_info["token_type"] = result["tokenType"]
                token_info["scope"] = ' '.join(result["scope"])
                token_info['expires_at'] = int(time.time()) + token_info['expires_in']
                token_info['refresh_token'] = result["accessToken"]
        except Exception as exc:
            log_exception(__name__, exc)
    return token_info
开发者ID:marcelveldt,项目名称:plugin.audio.spotify,代码行数:31,代码来源:utils.py


示例2: Dotter

class Dotter(object):
    def __init__(self,delay=100,symbol='.'):
        self.event=Event()
        self.delay=delay
        self.symbol=symbol
        self.status=False
    def __loop(self):
        while not self.event.is_set():
            stdout.write(self.symbol)
            stdout.flush()
            sleep(self.delay/1000)
    def start(self):
        if not self.status:
            self.event.clear()
            Thread(target=self.__loop).start()
            self.status=True
    def stop(self,newLine=True):
        if self.status:
            self.event.set()
            if newLine:
                stdout.write('\n')
            self.status=False
    def set(self,delay=None,symbol=None):
        if delay!=None:
            self.delay=delay
        if symbol!=None:
            self.symbol=symbol
        if self.status:
            self.stop(False)
            self.start()
开发者ID:0rovan,项目名称:dotting,代码行数:30,代码来源:__init__.py


示例3: __init__

class Actor:
    def __init__(self):
        self._mailbox = Queue()

    def send(self, msg):
        self._mailbox.put(msg)

    def recv(self):
        msg = self._mailbox.get()
        if msg is ActorExit:
            raise ActorExit()
        return msg

    def start(self):
        self._terminated = Event()
        t = Thread(target=self._bootstrap)
        t.daemon = True
        t.start()

    def _bootstrap(self):
        try:
            self.run()
        except ActorExit:
            pass
        finally:
            self._terminated.set()

    def join(self):
        self._terminated.wait()

    def run(self):
        while True:
            msg = self.recv()
开发者ID:bodii,项目名称:test-code,代码行数:33,代码来源:10.py


示例4: __init__

class ResponseEvent:
    """Event which is fired when the response is returned for a request.

        For each request sent this event is created.
        An application can wait for the event to create a blocking request.
    """
    def __init__(self):
        self.__evt = Event()

    def waiting(self):
        return not self.__evt.isSet()

    def waitForResponse(self, timeOut=None):
        """blocks until the response arrived or timeout is reached."""
        self.__evt.wait(timeOut)
        if self.waiting():
            raise Timeout()
        else:
            if self.response["error"]:
                raise Exception(self.response["error"])
            else:
                return self.response["result"]

    def handleResponse(self, resp):
        self.response = resp
        self.__evt.set()
开发者ID:Afey,项目名称:pyjs,代码行数:26,代码来源:__init__.py


示例5: DeferredResponse

class DeferredResponse( object ):
  """
  A deferred that resolves to a response from TSServer.
  """

  def __init__( self, timeout = RESPONSE_TIMEOUT_SECONDS ):
    self._event = Event()
    self._message = None
    self._timeout = timeout


  def resolve( self, message ):
    self._message = message
    self._event.set()


  def result( self ):
    self._event.wait( timeout = self._timeout )
    if not self._event.isSet():
      raise RuntimeError( 'Response Timeout' )
    message = self._message
    if not message[ 'success' ]:
      raise RuntimeError( message[ 'message' ] )
    if 'body' in message:
      return self._message[ 'body' ]
开发者ID:LukasScheucher,项目名称:ycmd,代码行数:25,代码来源:typescript_completer.py


示例6: __init__

    def __init__(self, pvName, mnemonic):
        """
        **Constructor**
        See :class:`py4syn.epics.StandardDevice`

        Parameters
        ----------
        pvName : `string`
            Power supply base naming of the PV (Process Variable)
        mnemonic : `string`
            Temperature controller mnemonic
        """
        super().__init__(mnemonic)

        self.device = Device(pvName + ':', ['termopar', 'target', 'status', 'stepNum',
                             'programTable', 'programming', 'run', 'stop', 'advance',
                             'setPatternCount', 'timeScale', 'level1', 'reset', 'pause',
                             'sendCommand'])

        self.programmingDone = Event()
        self.newTemperature = Event()
        self.newStep = Event()
        self.device.add_callback('programming', self.onProgrammingChange)
        self.device.add_callback('termopar', self.onTemperatureChange)
        self.device.add_callback('stepNum', self.onStepChange)
        self.timeScaleCache = self.device.get('timeScale')

        self.pvName = pvName
        self.rate = 5
        self.presetDone = False
开发者ID:douglasbeniz,项目名称:py4syn,代码行数:30,代码来源:OmronE5CKClass.py


示例7: sync

def sync(loop, func, *args, **kwargs):
    """ Run coroutine in loop running in separate thread """
    if not loop._running:
        try:
            return loop.run_sync(lambda: func(*args, **kwargs))
        except RuntimeError:  # loop already running
            pass

    from threading import Event
    e = Event()
    result = [None]
    error = [False]
    traceback = [False]

    @gen.coroutine
    def f():
        try:
            result[0] = yield gen.maybe_future(func(*args, **kwargs))
        except Exception as exc:
            logger.exception(exc)
            result[0] = exc
            error[0] = exc
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback[0] = exc_traceback
        finally:
            e.set()

    a = loop.add_callback(f)
    while not e.is_set():
        e.wait(1000000)
    if error[0]:
        six.reraise(type(error[0]), error[0], traceback[0])
    else:
        return result[0]
开发者ID:awesome-python,项目名称:distributed,代码行数:34,代码来源:utils.py


示例8: FromWatchdogWithSubservers_test

  def FromWatchdogWithSubservers_test( self ):
    all_servers_are_running = Event()

    def KeepServerAliveInAnotherThread():
      while not all_servers_are_running.is_set():
        try:
          self.GetRequest( 'ready' )
        except requests.exceptions.ConnectionError:
          pass
        finally:
          time.sleep( 0.1 )

    self.Start( idle_suicide_seconds = 2, check_interval_seconds = 1 )

    StartThread( KeepServerAliveInAnotherThread )

    try:
      filetypes = [ 'cs',
                    'go',
                    'java',
                    'javascript',
                    'typescript',
                    'rust' ]
      for filetype in filetypes:
        self.StartSubserverForFiletype( filetype )
      self.AssertServersAreRunning()
    finally:
      all_servers_are_running.set()

    self.AssertServersShutDown( timeout = SUBSERVER_SHUTDOWN_TIMEOUT + 10 )
    self.AssertLogfilesAreRemoved()
开发者ID:Valloric,项目名称:ycmd,代码行数:31,代码来源:shutdown_test.py


示例9: testMultipleLoad

    def testMultipleLoad(self):
        """
        In DropBox, the loading of multiple CLIs seems to
        lead to the wrong context being assigned to some
        controls.

        See #4749
        """
        import random
        from threading import Thread, Event

        event = Event()

        class T(Thread):
            def run(self, *args):
                pause = random.random()
                event.wait(pause)
                self.cli = CLI()
                self.cli.loadplugins()
                self.con = self.cli.controls["admin"]
                self.cmp = self.con.ctx

        threads = [T() for x in range(20)]
        for t in threads:
            t.start()
        event.set()
        for t in threads:
            t.join()

        assert len(threads) == len(set([t.cli for t in threads]))
        assert len(threads) == len(set([t.con for t in threads]))
        assert len(threads) == len(set([t.cmp for t in threads]))
开发者ID:sbesson,项目名称:openmicroscopy,代码行数:32,代码来源:test_cli.py


示例10: join

	def join(self,server,channel,nick=None,port=6667):
		channel = channel.lower()
		self.connect(server,port,nick)
		status = self.get_status(server)
		connected_servers = set(status['servers'])
		if not server in connected_servers:
			print("Not connected...")
		if channel in set(status['servers'][server]['channels']):
			print("Joined already.")
			return
		else:
			print("Joining",channel)
			e = Event()
			def channel_joined(addr,event):
				if event['kind']=='irc':
					if event['command']=='JOIN':
						if event['trailing'].lower()==channel:
							status['servers'][server]['channels'].append(channel)
							self.events.unlisten(server,channel_joined)
							e.set()
			self.events.listen(server,channel_joined)
			self.events.broadcast({
				'event':'irc.command:'+server,
				'command':"JOIN",
				"arguments":[channel]
			})
			e.wait()
开发者ID:tyler-elric,项目名称:ircp2p,代码行数:27,代码来源:chat.py


示例11: PeriodicTimer

class PeriodicTimer(object):

    def __init__(self, frequency=60, *args, **kwargs):
        self.is_stopped = Event()
        self.is_stopped.clear()

        self.interval = frequency
        self._timer = Timer(self.frequency, self._check_for_event, ())
        self._timer.daemon = True

    @property
    def interval(self):
        return self.frequency

    @interval.setter
    def interval(self, frequency):
        self.frequency = frequency
        self.stop()
        try:
            if self._timer:
                self._timer.cancel()
                del(self._timer)
        except AttributeError, ex:
            pass
        self._timer = Timer(self.frequency, self._check_for_event, ())
        return self.frequency
开发者ID:chrisleck-old-personal,项目名称:pytomation,代码行数:26,代码来源:periodic_timer.py


示例12: CheckForUpdates

class CheckForUpdates(Thread):

    INTERVAL = 24*60*60  # seconds
    daemon = True

    def __init__(self, parent):
        Thread.__init__(self)
        self.shutdown_event = Event()
        self.signal = Signal(parent)

    def run(self):
        while not self.shutdown_event.is_set():
            calibre_update_version = NO_CALIBRE_UPDATE
            plugins_update_found = 0
            try:
                version = get_newest_version()
                if version[:2] > numeric_version[:2]:
                    calibre_update_version = version
            except Exception as e:
                prints('Failed to check for calibre update:', as_unicode(e))
            try:
                update_plugins = get_plugin_updates_available(raise_error=True)
                if update_plugins is not None:
                    plugins_update_found = len(update_plugins)
            except Exception as e:
                prints('Failed to check for plugin update:', as_unicode(e))
            if calibre_update_version != NO_CALIBRE_UPDATE or plugins_update_found > 0:
                self.signal.update_found.emit(calibre_update_version, plugins_update_found)
            self.shutdown_event.wait(self.INTERVAL)

    def shutdown(self):
        self.shutdown_event.set()
开发者ID:artbycrunk,项目名称:calibre,代码行数:32,代码来源:update.py


示例13: TestInterruptible

class TestInterruptible(unittest.TestCase):
    """ Tests for interrupting cooperative threads """

    def test_interruptible_decorator(self):
        """ Tests for the @interruptible decorator. """
        self.quit_condition = False
        cancellation_point = lambda: _cancellation_point(
            lambda: self.quit_condition)
        self.thread_started = Event()

        @interruptible
        def never_ending(cancellation_point):
            self.thread_started.set()
            while True:
                time.sleep(0.1)
                cancellation_point()
        thread = Thread(target=never_ending, args=(cancellation_point, ))
        thread.start()
        self.thread_started.wait()
        self.quit_condition = True
        countdown = 10
        while thread.is_alive() and countdown > 0:
            time.sleep(0.1)
            countdown -= 1
        self.assertFalse(thread.is_alive())
开发者ID:MonamAgarwal,项目名称:final,代码行数:25,代码来源:test_interruptible.py


示例14: test_concurrent_rendering

def test_concurrent_rendering():
    '''Best-effort testing that concurrent multi-threaded rendering works.
    The test has no guarantees around being deterministic, but if it fails
    you know something is wrong with concurrent rendering. If it passes,
    things are probably working.'''
    err = None
    def func(sim, event):
        event.wait()
        sim.data.qpos[:] = 0.0
        sim.forward()
        img1 = sim.render(width=40, height=40, camera_name="camera1")
        img2 = sim.render(width=40, height=40, camera_name="camera2")
        try:
            assert np.sum(img1[:]) == 23255
            assert np.sum(img2[:]) == 12007
        except Exception as e:
            nonlocal err
            err = e

    model = load_model_from_xml(BASIC_MODEL_XML)
    sim = MjSim(model)
    sim.render(100, 100)
    event = Event()
    threads = []
    for _ in range(100):
        thread = Thread(target=func, args=(sim, event))
        threads.append(thread)
        thread.start()
    event.set()
    for thread in threads:
        thread.join()
    assert err is None, "Exception: %s" % (str(err))
开发者ID:m-j-mcdonald,项目名称:mujoco-py,代码行数:32,代码来源:test_cymj.py


示例15: TriggerEventWait

    def TriggerEventWait(
        self,
        suffix,
        payload=None,
        prefix="Main",
        source=eg
    ):
        event = EventGhostEvent(suffix, payload, prefix, source)
        if event.source in self.filters:
            for filterFunc in self.filters[event.source]:
                if filterFunc(event) is True:
                    return event
        executed = Event()

        def Execute():
            try:
                event.Execute()
            finally:
                executed.set()

        def Transfer():
            ActionThreadCall(Execute)
            event.SetShouldEnd()

        self.AppendAction(Transfer)
        executed.wait(5.0)
        if not executed.isSet():
            eg.PrintWarningNotice(
                "timeout TriggerEventWait\n", traceback.format_stack()
            )
        return event
开发者ID:topic2k,项目名称:EventGhost,代码行数:31,代码来源:EventThread.py


示例16: Task

class Task(object):
    def __init__(self, name, start_time, calc_next_time, func):
        """
        Initialize a Task.
       
        Arguments:
        name            - Name of task.
        start_time      - First time for task to run
        calc_next_time  - Function to calculate the time of next run,
                          gets one argument, the last run time as a datetime.
                          Returns None when task should no longer be run
        func            - A function to run
        """
        self.name = name
        self.start_time = start_time
        self.scheduled_time = start_time
        self.calc_next_time = calc_next_time
        self.func = func
        self.halt_flag = Event()
       
    def run(self):
        logging.debug("Running %s task, scheduled at: %s" % (self.name, self.scheduled_time,))
        if not self.halt_flag.isSet():
            try:
                try:
                    self.func()
                except:
                    raise
            finally:
                self.scheduled_time = self.calc_next_time(self.scheduled_time)
                logging.debug("Scheduled next run of %s for: %s" % (self.name, self.scheduled_time,))
           
    def halt(self):
        self.halt_flag.set()
开发者ID:theclai,项目名称:mataramprayertimes,代码行数:34,代码来源:scheduler.py


示例17: test_delayed_body_read_timeout

    def test_delayed_body_read_timeout(self):
        timed_out = Event()

        def socket_handler(listener):
            sock = listener.accept()[0]
            buf = b''
            body = 'Hi'
            while not buf.endswith(b'\r\n\r\n'):
                buf = sock.recv(65536)
            sock.send(('HTTP/1.1 200 OK\r\n'
                       'Content-Type: text/plain\r\n'
                       'Content-Length: %d\r\n'
                       '\r\n' % len(body)).encode('utf-8'))

            timed_out.wait()
            sock.send(body.encode('utf-8'))
            sock.close()

        self._start_server(socket_handler)
        pool = HTTPConnectionPool(self.host, self.port)

        response = yield From(pool.urlopen('GET', '/', retries=0, preload_content=False,
                                timeout=Timeout(connect=1, read=0.1)))
        try:
            self.aioAssertRaises(ReadTimeoutError, response.read)
        finally:
            timed_out.set()
开发者ID:andrewleech,项目名称:yieldfromUrllib3_trollius,代码行数:27,代码来源:test_socketlevel.py


示例18: WaitApp

class WaitApp (object):
  def __init__ (self):
    # self.event = event
    self.ev = Event( )
    self.loop = GLib.MainLoop( )
    self.expired = False

  def handle_emitted (self, status):
    print "emitted", status, self

  def handle_event (self):
    print "event", self.loop
    self.loop.quit( )


  def until (self, event, timeout=None):
    self.event = event
    self.event.Do.connect(self.handle_event)
    self.event.Emit.connect(self.handle_emitted)
    self.background = Thread(target=self.pending, args=(timeout, self.loop.quit))
    self.background.daemon = True
    self.background.start( )
    self.loop.run( )

  def pending (self, timeout, quit):
    print "starting background, waiting for ", timeout
    self.ev.wait(timeout)
    quit( )
    self.expired = True
    print "Failed to find event within", timeout
开发者ID:openaps,项目名称:oacids,代码行数:30,代码来源:until.py


示例19: TestInterruptibleDecorator

class TestInterruptibleDecorator(TestCase):

    def setUp(self):
        self.quit_condition = False
        self.thread_started = Event()

    @interruptible
    def never_ending(self, cancellation_point):
        self.thread_started.set()
        while True:
            time.sleep(0.01)
            cancellation_point()

    def test_interruptible_decorator(self):
        """ Tests for the @interruptible decorator. """
        thread = Thread(target=self.never_ending, args=(
            lambda: _cancellation_point(lambda: self.quit_condition),))
        thread.start()

        # Wait until thread comes to live
        self.thread_started.wait()

        # Ask to it to quit within 20ms
        self.quit_condition = True
        time.sleep(0.02)

        # Thread is finished
        self.assertFalse(thread.is_alive())
开发者ID:abseabse,项目名称:gtg,代码行数:28,代码来源:test_interruptible.py


示例20: _score_scenes

    def _score_scenes(self, mov, scene_list, score_obj, analysis_budget):
        '''Get all the scenes scored.

        Results stored in score_obj
        '''
        frame_q = Queue.Queue(maxsize=100)
        halter = Event()

        threads = [
            Thread(target=self._frame_extractor,
                   args=(mov, scene_list, frame_q, halter))]
        for i in range(options.workers):
            threads.append(Thread(target=self._worker,
                                  args=(score_obj, frame_q, halter)))

        for t in threads:
            t.daemon = True
            t.start()

        # Run the frame scoring until we are out of time
        if not halter.wait(analysis_budget):
            _log.info('Out of time sampling frames')
            halter.set()

        for t in threads:
            t.join()

        _log.info('Finished scoring scenes')
开发者ID:neonopen,项目名称:aquila-python,代码行数:28,代码来源:clip_finder.py



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python threading.Lock类代码示例发布时间:2022-05-27
下一篇:
Python threading.Condition类代码示例发布时间: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