本文整理汇总了Python中greenlet.getcurrent方法的典型用法代码示例。如果您正苦于以下问题:Python greenlet.getcurrent方法的具体用法?Python greenlet.getcurrent怎么用?Python greenlet.getcurrent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类greenlet
的用法示例。
在下文中一共展示了greenlet.getcurrent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __new__
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def __new__(cls, func, sentinel=''):
if greenlet is None:
raise RuntimeError('IterI requires greenlet support')
stream = object.__new__(cls)
stream._parent = greenlet.getcurrent()
stream._buffer = []
stream.closed = False
stream.sentinel = sentinel
stream.pos = 0
def run():
func(stream)
stream.close()
g = greenlet.greenlet(run, stream._parent)
while 1:
rv = g.switch()
if not rv:
return
yield rv[0]
示例2: synclize
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def synclize(func):
coro = coroutine(func)
@wraps(func)
def _sync_call(*args, **kwargs):
child_gr = greenlet.getcurrent()
main = child_gr.parent
assert main, "only run in child greenlet"
def callback(future):
if future.exc_info():
child_gr.throw(*future.exc_info())
elif future.exception():
child_gr.throw(future.exception())
else:
child_gr.switch(future.result())
IOLoop.current().add_future(coro(*args, **kwargs), callback)
return main.switch()
return _sync_call
示例3: handle_system_error
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def handle_system_error(self, type, value):
current = getcurrent()
if current is self or current is self.parent or self.loop is None:
self.parent.throw(type, value)
else:
# in case system error was handled and life goes on
# switch back to this greenlet as well
cb = None
try:
cb = self.loop.run_callback(current.switch)
except:
traceback.print_exc()
try:
self.parent.throw(type, value)
finally:
if cb is not None:
cb.stop()
示例4: wait
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def wait(self, watcher):
"""
Wait until the *watcher* (which should not be started) is ready.
The current greenlet will be unscheduled during this time.
.. seealso:: :class:`gevent.core.io`, :class:`gevent.core.timer`,
:class:`gevent.core.signal`, :class:`gevent.core.idle`, :class:`gevent.core.prepare`,
:class:`gevent.core.check`, :class:`gevent.core.fork`, :class:`gevent.core.async`,
:class:`gevent.core.child`, :class:`gevent.core.stat`
"""
waiter = Waiter()
unique = object()
watcher.start(waiter.switch, unique)
try:
result = waiter.get()
if result is not unique:
raise InvalidSwitchError('Invalid switch into %s: %r (expected %r)' % (getcurrent(), result, unique))
finally:
watcher.stop()
示例5: run
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def run(self):
"""
Entry-point to running the loop. This method is called automatically
when the hub greenlet is scheduled; do not call it directly.
:raises LoopExit: If the loop finishes running. This means
that there are no other scheduled greenlets, and no active
watchers or servers. In some situations, this indicates a
programming error.
"""
assert self is getcurrent(), 'Do not call Hub.run() directly'
while True:
loop = self.loop
loop.error_handler = self
try:
loop.run()
finally:
loop.error_handler = None # break the refcount cycle
self.parent.throw(LoopExit('This operation would block forever', self))
# this function must never return, as it will cause switch() in the parent greenlet
# to return an unexpected value
# It is still possible to kill this greenlet with throw. However, in that case
# switching to it is no longer safe, as switch will return immediatelly
示例6: __new__
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def __new__(cls, func, sentinel=""):
if greenlet is None:
raise RuntimeError("IterI requires greenlet support")
stream = object.__new__(cls)
stream._parent = greenlet.getcurrent()
stream._buffer = []
stream.closed = False
stream.sentinel = sentinel
stream.pos = 0
def run():
func(stream)
stream.close()
g = greenlet.greenlet(run, stream._parent)
while 1:
rv = g.switch()
if not rv:
return
yield rv[0]
示例7: pause
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def pause(self, timeout=-1):
if timeout > -1:
item = self.scheduled.add(
timeout,
getcurrent(),
vanilla.exception.Timeout('timeout: %s' % timeout))
assert getcurrent() != self.loop, "cannot pause the main loop"
resume = None
try:
resume = self.loop.switch()
finally:
if timeout > -1:
if isinstance(resume, vanilla.exception.Timeout):
raise resume
# since we didn't timeout, remove ourselves from scheduled
self.scheduled.remove(item)
# TODO: rework State's is set test to be more natural
if self.stopped.recver.ready:
raise vanilla.exception.Stop(
'Hub stopped while we were paused. There must be a deadlock.')
return resume
示例8: sleep
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def sleep(self, ms=1):
"""
Pauses the current green thread for *ms* milliseconds::
p = h.pipe()
@h.spawn
def _():
p.send('1')
h.sleep(50)
p.send('2')
p.recv() # returns '1'
p.recv() # returns '2' after 50 ms
"""
self.scheduled.add(ms, getcurrent())
self.loop.switch()
示例9: _capture_profile
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def _capture_profile(fname=''):
if not fname:
yappi.set_clock_type('cpu')
# We need to set context to greenlet to profile greenlets
# https://bitbucket.org/sumerc/yappi/pull-requests/3
yappi.set_context_id_callback(
lambda: id(greenlet.getcurrent()))
yappi.set_context_name_callback(
lambda: greenlet.getcurrent().__class__.__name__)
yappi.start()
else:
yappi.stop()
stats = yappi.get_func_stats()
# User should provide filename. This file with a suffix .prof
# will be created in temp directory.
try:
stats_file = os.path.join(tempfile.gettempdir(), fname + '.prof')
stats.save(stats_file, "pstat")
except Exception as e:
print("Error while saving the trace stats ", str(e))
finally:
yappi.clear_stats()
示例10: wrap_socket
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def wrap_socket(self, sock, server_side=False,
do_handshake_on_connect=True,
suppress_ragged_eofs=True,
server_hostname=None, session=None):
child_gr = greenlet.getcurrent()
main = child_gr.parent
assert main is not None, "Execut must be running in child greenlet"
def finish(future):
if (hasattr(future, "_exc_info") and future._exc_info is not None) \
or (hasattr(future, "_exception") and future._exception is not None):
child_gr.throw(future.exception())
else:
child_gr.switch(future.result())
future = sock.start_tls(False, self._ctx, server_hostname=server_hostname, connect_timeout=self._connection.connect_timeout)
future.add_done_callback(finish)
return main.switch()
示例11: handle_system_error
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def handle_system_error(self, type, value):
current = getcurrent()
if current is self or current is self.parent or self.loop is None:
self.parent.throw(type, value)
else:
# in case system error was handled and life goes on
# switch back to this greenlet as well
cb = None
try:
cb = self.loop.run_callback(current.switch)
except: # pylint:disable=bare-except
traceback.print_exc(file=self.exception_stream)
try:
self.parent.throw(type, value)
finally:
if cb is not None:
cb.stop()
示例12: wait
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def wait(self):
"""Invoked from each client's thread to wait for the next frame."""
ident = get_ident()
if ident not in self.events:
# this is a new client
# add an entry for it in the self.events dict
# each entry has two elements, a threading.Event() and a timestamp
self.events[ident] = [threading.Event(), time.time()]
return self.events[ident][0].wait()
示例13: clear
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def clear(self):
"""Invoked from each client's thread after a frame was processed."""
self.events[get_ident()][0].clear()
示例14: get
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def get(self):
return id(greenlet.getcurrent())
示例15: watch
# 需要导入模块: import greenlet [as 别名]
# 或者: from greenlet import getcurrent [as 别名]
def watch(self, callback):
current = greenlet.getcurrent()
tid = self.get()
if hasattr(current, 'link'):
# This is a Gevent Greenlet (capital G), which inherits from
# greenlet and provides a 'link' method to detect when the
# Greenlet exits.
link = SpawnedLink(callback)
current.rawlink(link)
self._refs[tid] = link
else:
# This is a non-Gevent greenlet (small g), or it's the main
# greenlet.
self._refs[tid] = weakref.ref(current, callback)