本文整理汇总了Python中threading.Event类的典型用法代码示例。如果您正苦于以下问题:Python Event类的具体用法?Python Event怎么用?Python Event使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Event类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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()
示例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()
示例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()
示例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' ]
示例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
示例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]
示例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()
示例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]))
示例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()
示例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
示例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()
示例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())
示例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))
示例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