本文整理汇总了Python中stackless.getcurrent函数的典型用法代码示例。如果您正苦于以下问题:Python getcurrent函数的具体用法?Python getcurrent怎么用?Python getcurrent使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getcurrent函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: SendEventWithoutTheStars
def SendEventWithoutTheStars(self, eventid, args, keywords = None):
if keywords is None:
keywords = {}
if not eventid.startswith('Do'):
self.LogError('SendEvent called with event ', eventid, ". All events sent via SendEvent should start with 'Do'")
self.LogError("Not only is the programmer responsible for this a 10z3r, but he wears his mother's underwear as well")
log.LogTraceback()
if not self.notify.get(eventid, []) and not self.notifyObs.get(eventid, []):
self.LogInfo("Orphan'd event. ", eventid, "doesn't have any listeners")
shouldLogMethodCalls = self.ShouldLogMethodCalls()
if shouldLogMethodCalls:
if IsFullLogging():
self.LogMethodCall('SendEvent(', eventid, ',*args=', args, ',**kw=', keywords, ')')
else:
self.LogMethodCall('SendEvent(', eventid, ')')
prefix = blue.pyos.taskletTimer.GetCurrent() + '::SendEvent_' + eventid + '::'
old_block_trap = stackless.getcurrent().block_trap
stackless.getcurrent().block_trap = 1
ret = []
try:
for srv in self.notify.get(eventid, []):
try:
logname = prefix + self.GetLogName(srv)
if ObjectShouldReceiveMessages(srv):
if shouldLogMethodCalls:
self.LogMethodCall('Calling ', logname)
ret.append(ClockThisWithoutTheStars(logname, getattr(srv, eventid), args, keywords))
elif shouldLogMethodCalls:
self.LogMethodCall('Skipping ', logname, ' (service not running)')
except StandardError:
self.LogError('In %s.%s' % (getattr(srv, '__guid__', logname), eventid))
log.LogException()
sys.exc_clear()
notifiedToRemove = []
for weakObj in self.notifyObs.get(eventid, []):
obj = weakObj()
if obj is None:
notifiedToRemove.append(weakObj)
else:
try:
if shouldLogMethodCalls:
logname = prefix + str(obj)
self.LogMethodCall('Calling ', logname)
apply(getattr(obj, eventid), args, keywords)
except StandardError:
self.LogError('In %s.%s' % (getattr(weakObj, '__guid__', self.GetLogName(weakObj)), eventid))
log.LogException()
sys.exc_clear()
for toRemove in notifiedToRemove:
if toRemove in self.notifyObs[eventid]:
self.notifyObs[eventid].remove(toRemove)
finally:
bt = 0
if old_block_trap:
bt = 1
stackless.getcurrent().block_trap = bt
return tuple(ret)
开发者ID:connoryang,项目名称:dec-eve-serenity,代码行数:60,代码来源:serviceManager.py
示例2: testSendInsert
def testSendInsert(self):
channel_obj = stackless.channel()
self.assertEqual(None, channel_obj.queue)
tasklet1 = stackless.tasklet(lambda: 1 / 0)()
tasklet2 = stackless.tasklet(channel_obj.receive)()
tasklet2.run()
self.assertRaisesStr(
RuntimeError, 'You cannot remove a blocked tasklet.',
tasklet2.remove)
# channel_obj.send inserts tasklet2 after current, and since tasklet1 was
# after current, the insertion runs tasklet1 eventually, which triggers
# the ZeroDivisionError, propagated to current (== main).
self.assertRaises(ZeroDivisionError, channel_obj.send, 0)
self.assertEqual(1, stackless.getruncount())
self.assertEqual(None, channel_obj.queue)
channel_obj.preference = 1 # Prefer the sender.
tasklet1 = stackless.tasklet(lambda: 1 / 0)()
tasklet2 = stackless.tasklet(channel_obj.receive)()
self.assertEqual(False, tasklet2.blocked)
self.assertEqual(True, tasklet2.scheduled)
tasklet2.run()
self.assertEqual(True, tasklet2.blocked)
self.assertEqual(True, tasklet2.scheduled)
self.assertEqual(tasklet1, stackless.getcurrent().next)
self.assertEqual(None, channel_obj.send(0))
self.assertEqual(tasklet1, stackless.getcurrent().next)
self.assertEqual(tasklet2, stackless.current.prev)
tasklet1.remove()
stackless.schedule()
开发者ID:breezechen,项目名称:syncless,代码行数:30,代码来源:stackless_test.py
示例3: stack
def stack(*argl, **argd):
if log_level > LOG_LEVEL_ERROR:
return
print "S", str(id(stackless.getcurrent())), "| ************************************************************"
print "S", str(id(stackless.getcurrent())), '|', _log(*argl, **argd)
traceback.print_stack()
print "S", str(id(stackless.getcurrent())), "| ************************************************************"
开发者ID:zhaozw,项目名称:hall37,代码行数:7,代码来源:log.py
示例4: CreateServiceInstance
def CreateServiceInstance(self, serviceName):
old_block_trap = stackless.getcurrent().block_trap
stackless.getcurrent().block_trap = 1
try:
try:
createName, createClass = self.classmapWithReplacements[serviceName]
except KeyError:
self._BuildClassMap()
try:
createName, createClass = self.classmapWithReplacements[serviceName]
except KeyError:
raise ServiceNotFound(serviceName)
if createName != serviceName:
print 'Replacing service %r with %r' % (serviceName, createName)
replaceService = getattr(createClass, '__replaceservice__', None)
if replaceService is not None and replaceService != serviceName:
raise RuntimeError('Must not start %s directly as it replaces %s' % (serviceName, replaceService))
srv = createClass()
if not isinstance(srv, service.Service):
raise RuntimeError('Service name %r does not resolve to a service class (%r)' % (serviceName, createClass))
srv.__servicename__ = serviceName
srv.session = base.GetServiceSession(serviceName)
self.VerifyServiceExports(srv, serviceName)
return srv
finally:
stackless.getcurrent().block_trap = old_block_trap
开发者ID:connoryang,项目名称:dec-eve-serenity,代码行数:27,代码来源:serviceManager.py
示例5: testNonBlockingReceive
def testNonBlockingReceive(self):
''' Test that when there is a waiting sender, we can receive without blocking with normal channel behaviour. '''
originalValue = 1
# Function to block when run in a tasklet.
def f(testChannel, valueToSend):
testChannel.send(valueToSend)
# Get the tasklet blocked on the channel.
channel = stackless.channel()
tasklet = stackless.tasklet(f)(channel, originalValue)
tasklet.run()
# Make sure that the current tasklet cannot block when it tries to receive. We do not want
# to exit this test having clobbered the block trapping value, so we make sure we restore
# it.
oldBlockTrap = stackless.getcurrent().block_trap
try:
stackless.getcurrent().block_trap = True
value = channel.receive()
finally:
stackless.getcurrent().block_trap = oldBlockTrap
tasklet.kill()
self.assertEqual(value, originalValue, "We received a value, but it was not the one we sent. Completely unexpected.")
开发者ID:d11,项目名称:rts,代码行数:26,代码来源:test_channel.py
示例6: output
def output():
while 1:
url=chan.receive()
print url
f=urllib2.urlopen(url)
#print f.read()
print stackless.getcurrent()
开发者ID:liumeixia,项目名称:xiaworkspace,代码行数:7,代码来源:ping.py
示例7: forceStart
def forceStart(serviceName, serviceType):
global runningServices
import stackless
import service
old_block_trap = stackless.getcurrent().block_trap
stackless.getcurrent().block_trap = 1
try:
oldInstance = runningServices.get(serviceName, None)
if oldInstance:
forceStop(serviceName)
result = serviceType()
setattr(result, "state", service.SERVICE_RUNNING)
result = makeServiceThunk(result)
runningServices[serviceName] = result
ne = getattr(result, "__notifyevents__", [])
if len(ne):
for evt in ne:
if (not hasattr(result, evt)):
log("Missing event handler for %r on %r", evt, result)
else:
nl = sm.notify.setdefault(evt, list())
nl.append(result)
return result
finally:
stackless.getcurrent().block_trap = old_block_trap
开发者ID:Sancus,项目名称:shootbluesscripts,代码行数:29,代码来源:common.service.py
示例8: CallWrapper
def CallWrapper(*args, **kwds):
current = stackless.getcurrent()
current.startTime = blue.os.GetWallclockTimeNow()
oldtimer = PushTimer(current.context)
exc = None
try:
try:
return method(*args, **kwds)
except TaskletExit as e:
import log
t = stackless.getcurrent()
log.general.Log('tasklet (%s) %s exiting with %r' % (t.tasklet_id, t, e), log.LGINFO)
except SystemExit as e:
import log
log.general.Log('system %s exiting with %r' % (stackless.getcurrent(), e), log.LGINFO)
except Exception:
import log
print >> debugFile, 'Unhandled exception in tasklet', repr(stackless.getcurrent())
traceback.print_exc(file=debugFile)
exc = sys.exc_info()
log.LogException('Unhandled exception in %r' % stackless.getcurrent())
return
except:
traceback.print_exc()
traceback.print_exc(file=debugFile)
if exc:
traceback.print_exception(exc[0], exc[1], exc[2])
traceback.print_exception(exc[0], exc[1], exc[2], file=debugFile)
finally:
exc = None
PopTimer(oldtimer)
current.endTime = blue.os.GetWallclockTimeNow()
开发者ID:Pluckyduck,项目名称:eve,代码行数:33,代码来源:bluepy.py
示例9: get_dict
def get_dict(self):
d = object.__getattribute__(self, "__dict__")["_tasklets"]
try:
a = d[stackless.getcurrent()]
except KeyError:
a = {}
d[stackless.getcurrent()] = a
return a
开发者ID:breezechen,项目名称:stacklessexamples,代码行数:8,代码来源:util.py
示例10: release
def release(self, override = False):
with atomic():
if self.strict and not override:
if stackless.getcurrent() not in self.threads:
raise RuntimeError, 'wrong tasklet releasing strict semaphore'
self.count += 1
self.threads.remove(stackless.getcurrent())
self.lockedWhen = None
self._pump()
开发者ID:Pluckyduck,项目名称:eve,代码行数:9,代码来源:uthread.py
示例11: writer
def writer(n):
for i in range(n):
with self.lock.acquired():
inlock.append(stackless.getcurrent())
for j in xrange(random.randint(1, 3)):
stackless.schedule()
stats.append(inlock[:])
inlock.remove(stackless.getcurrent())
开发者ID:connoryang,项目名称:dec-eve-serenity,代码行数:9,代码来源:locks_unittest.py
示例12: ProcessDispatchOrders
def ProcessDispatchOrders(self, orders):
ownersToPrime, tickersToPrime, allyTickersToPrime, stuffToAdd, newState, locationsToPrime = orders
if locationsToPrime:
try:
cfg.evelocations.Prime(locationsToPrime)
except StandardError:
self.LogError('In michelle.Dispatcher')
log.LogException()
sys.exc_clear()
if ownersToPrime:
try:
cfg.eveowners.Prime(ownersToPrime)
except StandardError:
self.LogError('In michelle.Dispatcher')
log.LogException()
sys.exc_clear()
if tickersToPrime:
try:
cfg.corptickernames.Prime(tickersToPrime)
except StandardError:
self.LogError('In michelle.Dispatcher')
log.LogException()
sys.exc_clear()
if allyTickersToPrime:
try:
cfg.allianceshortnames.Prime(allyTickersToPrime)
except StandardError:
self.LogError('In michelle.Dispatcher')
log.LogException()
sys.exc_clear()
realBalls = {}
for ballID, slimItem in stuffToAdd:
try:
if self.__bp and ballID in self.__bp.balls:
ball = self.__bp.balls[ballID]
if not self.__bp.slimItems.has_key(ballID):
realBalls[ballID] = (ball, slimItem)
self.__bp.slimItems[ballID] = slimItem
except StandardError:
self.LogError('In michelle.Dispatcher')
log.LogException()
sys.exc_clear()
if len(realBalls):
t = stackless.getcurrent()
timer = t.PushTimer(blue.pyos.taskletTimer.GetCurrent() + '::DoBallsAdded')
sm.SendEvent('DoBallsAdded', realBalls.values())
t.PopTimer(timer)
if newState is not None:
t = stackless.getcurrent()
timer = t.PushTimer(blue.pyos.taskletTimer.GetCurrent() + '::OnNewState')
sm.ScatterEvent('OnNewState', newState)
t.PopTimer(timer)
开发者ID:Pluckyduck,项目名称:eve,代码行数:57,代码来源:michelle.py
示例13: release
def release(self):
if self.__reentrantRefs:
# MEB: assert self.thread is stackless.getcurrent()
assert self.thread is stackless.getcurrent() or IsCurrentSynonymOf(self.thread)
# MEB: if self.thread is not stackless.getcurrent():
if not (self.thread is stackless.getcurrent() or IsCurrentSynonymOf(self.thread)):
raise RuntimeError, "wrong tasklet releasing reentrant CriticalSection"
self.__reentrantRefs -= 1
else:
Semaphore.release(self)
开发者ID:breezechen,项目名称:stacklessexamples,代码行数:10,代码来源:uthread.py
示例14: testTempval
def testTempval(self):
def Worker(items):
items.append(stackless.schedule())
items.append(stackless.schedule(None))
items.append(stackless.schedule('foo'))
items.append(stackless.schedule(42))
items = []
tasklet_obj = stackless.tasklet(Worker)(items)
self.assertEqual(None, tasklet_obj.tempval)
self.assertEqual([], items)
stackless.current.tempval = 5
self.assertEqual(stackless.getcurrent(), stackless.schedule())
self.assertEqual(None, stackless.current.tempval)
self.assertEqual(tasklet_obj, tasklet_obj.tempval)
self.assertEqual([], items)
stackless.schedule()
self.assertEqual(None, tasklet_obj.tempval)
self.assertEqual([tasklet_obj], items)
stackless.schedule()
self.assertEqual('foo', tasklet_obj.tempval)
self.assertEqual([tasklet_obj, None], items)
tasklet_obj.tempval = False
stackless.schedule()
self.assertEqual([tasklet_obj, None, False], items)
self.assertEqual(42, tasklet_obj.tempval)
stackless.schedule()
self.assertEqual([tasklet_obj, None, False, 42], items)
# Upon TaskletExit.
self.assertEqual(None, tasklet_obj.tempval)
self.assertEqual(1, stackless.getruncount())
self.assertEqual(stackless.getcurrent(), stackless.schedule())
self.assertEqual(None, stackless.current.tempval)
self.assertEqual(43, stackless.schedule(43))
# This seems to be a strange Stackless quirk, this should be 43.
self.assertEqual(None, stackless.getcurrent().tempval)
self.assertEqual(54, stackless.schedule_remove(54))
self.assertEqual(None, stackless.current.tempval)
def Worker2(items, main_tasklet):
items.append(stackless.getcurrent().tempval)
items.append(stackless.schedule(44))
items.append(stackless.current.tempval)
main_tasklet.insert()
del items[:]
stackless.tasklet(Worker2)(items, stackless.getcurrent())
self.assertEqual(55, stackless.schedule_remove(55))
self.assertEqual(None, stackless.current.tempval)
self.assertEqual([None, 44, None], items)
self.assertRaisesStr(AssertionError, '', stackless.schedule,
stackless.bomb(AssertionError))
self.assertRaisesStr(AssertionError, 'foo', stackless.schedule,
stackless.bomb(AssertionError, 'foo'))
开发者ID:breezechen,项目名称:syncless,代码行数:55,代码来源:stackless_test.py
示例15: Parallel
def Parallel(funcs,exceptionHandler=None,maxcount=30):
'''
Executes in parallel all the function calls specified in the list/tuple 'funcs', but returns the
return values in the order of the funcs list/tuple. If an exception occurs, only the first exception
will reach you. The rest will dissapear in a puff of logic.
Each 'func' entry should be a tuple/list of:
1. a function to call
2. a tuple of arguments to call it with
3. optionally, a dict of keyword args to call it with.
'''
if not funcs:
return
context = "ParallelHelper::"+getattr(stackless.getcurrent(),"context","???")
ch = stackless.channel(), id(stackless.getcurrent())
ret = [ None ] * len(funcs)
n = len(funcs)
if n > maxcount:
n = maxcount
for i in range(n):
if type(funcs[i]) != types.TupleType:
raise RuntimeError("Parallel requires a list/tuple of (function, args tuple, optional keyword dict,)")
Pool(context, ParallelHelper, ch, i, funcs[i])
for i in range(len(funcs)):
ok, bunch = ch[0].receive()
if ok:
idx,val = bunch
if len(funcs[i])==4:
ret[idx] = (funcs[i][3], val,)
else:
ret[idx] = val
else:
try:
raise bunch[0],bunch[1],bunch[2]
except StandardError:
if exceptionHandler:
exctype, exc, tb = sys.exc_info()
try:
try:
apply( exceptionHandler, (exc,) )
except StandardError:
raise exc, None, tb
finally:
exctype, exc, tb = None, None, None
else:
StackTrace()
raise
if n<len(funcs):
if type(funcs[n]) != types.TupleType:
raise RuntimeError("Parallel requires a list/tuple of (function, args tuple, optional keyword dict,)")
Pool(context, ParallelHelper, ch, n, funcs[n])
n+=1
return ret
开发者ID:breezechen,项目名称:stacklessexamples,代码行数:55,代码来源:uthread.py
示例16: __acquire_inner
def __acquire_inner(self):
while 1:
try:
if self.lockers.has_key(stackless.getcurrent()):
self.lockers[stackless.getcurrent()] += 1
else:
self.lockers[stackless.getcurrent()] = 1
break
except:
StackTrace()
sys.exc_clear()
开发者ID:breezechen,项目名称:stacklessexamples,代码行数:11,代码来源:uthread.py
示例17: acquire
def acquire(self):
if self.strict:
assert self.thread is not stackless.getcurrent()
if self.thread is stackless.getcurrent():
raise RuntimeError, "tasklet deadlock, acquiring tasklet holds strict semaphore"
self.count -= 1
if self.count < 0:
self.waiting.receive()
self.lockedWhen = time.time()
self.thread = stackless.getcurrent()
开发者ID:breezechen,项目名称:stacklessexamples,代码行数:11,代码来源:uthread.py
示例18: try_acquire
def try_acquire(self):
with atomic():
if self.strict:
if self.count <= 0 and stackless.getcurrent() in self.threads:
raise RuntimeError, 'tasklet deadlock, acquiring tasklet holds strict semaphore'
if self.count > 0:
self.count -= 1
self.lockedWhen = blue.os.GetWallclockTime()
self.threads.append(stackless.getcurrent())
return True
return False
开发者ID:Pluckyduck,项目名称:eve,代码行数:11,代码来源:uthread.py
示例19: lock
def lock(self, relockKey=None):
if self._islock == True:
if self._fttask == stackless.getcurrent():
self.relock += 1
return
if self.relockKey != None and self.relockKey == relockKey:
self.relock += 1
return
self.receive()
self._islock = True
self._fttask = stackless.getcurrent()
开发者ID:zhaozw,项目名称:hall37,代码行数:11,代码来源:lock.py
示例20: ChainEventWithoutTheStars
def ChainEventWithoutTheStars(self, eventid, args, keywords = None):
if keywords is None:
keywords = {}
if not eventid.startswith('Process'):
self.LogError('ChainEvent called with event ', eventid, ". All events sent via ChainEvent should start with 'Process'")
self.LogError("Not only is the programmer responsible for this a 10z3r, but he wears his mother's underwear as well")
log.LogTraceback()
if stackless.getcurrent().block_trap or stackless.getcurrent().is_main:
raise RuntimeError("ChainEvent is blocking by design, but you're block trapped. You have'll have to find some alternative means to do Your Thing, dude.")
if not self.notify.get(eventid, []) and not self.notifyObs.get(eventid, []):
self.LogInfo("Orphan'd event. ", eventid, "doesn't have any listeners")
shouldLogMethodCalls = self.ShouldLogMethodCalls()
if shouldLogMethodCalls:
self.LogMethodCall('ChainEvent(', eventid, ',*args=', args, ',**kw=', keywords, ')')
prefix = blue.pyos.taskletTimer.GetCurrent() + '::ChainEvent_' + eventid + '::'
ret = []
for srv in self.notify.get(eventid, []):
contextName = self.GetLogName(srv)
try:
logname = prefix + contextName
if ObjectShouldReceiveMessages(srv):
if shouldLogMethodCalls:
self.LogMethodCall('Calling ', logname)
retval = ClockThisWithoutTheStars(logname, getattr(srv, eventid), args, keywords)
ret.append(retval)
elif shouldLogMethodCalls:
self.LogMethodCall('Skipping ', logname, ' (service not running)')
except StandardError:
self.LogError('In %s.%s' % (contextName, eventid))
log.LogException()
sys.exc_clear()
notifiedToRemove = []
for weakObj in self.notifyObs.get(eventid, []):
obj = weakObj()
if obj is None:
notifiedToRemove.append(weakObj)
else:
contextName = self.GetLogName(weakObj)
try:
logname = prefix + contextName
if shouldLogMethodCalls:
self.LogMethodCall('Calling ', prefix + str(obj))
ClockThisWithoutTheStars(logname, getattr(obj, eventid), args, keywords)
except StandardError:
self.LogError('In %s.%s:' % (contextName, eventid))
log.LogException()
sys.exc_clear()
for toRemove in notifiedToRemove:
if toRemove in self.notifyObs[eventid]:
self.notifyObs[eventid].remove(toRemove)
return tuple(ret)
开发者ID:connoryang,项目名称:dec-eve-serenity,代码行数:54,代码来源:serviceManager.py
注:本文中的stackless.getcurrent函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论