打印函数运行日志的装饰器
    :param func:
    :return:
557463
def log(func):
    

    # wraps 这个装饰器会将 func 的 doc 和 __name__ 复制过来
    # 否则在 wrapper 中调用 func.__name__ 输出的就是 wrapper
    @wraps(func)
    def wrapper(*args, **kwargs):
        print('before call %s' % func.__name__)
        ret = func(*args, **kwargs)
        print('after call %s' % func.__name__)
        return ret

    return wrapper
124479
def call_func(self, fun, **kwargs):
        '''
        
        '''
        return self.low(fun, kwargs, print_event=kwargs.get('print_event', True), full_return=kwargs.get('full_return', False))
1021523
def threaded(func):
    

    def dec(self, *args, **kwargs):
        thread.start_new_thread(func, (self, ) + args, kwargs)

    return dec
1334096
def with_log(func):
    
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        """Inject `log` argument into wrapped function.

        :param list args: Pass through all positional arguments.
        :param dict kwargs: Pass through all keyword arguments.
        """
        decorator_logger = logging.getLogger('@with_log')
        decorator_logger.debug('Entering %s() function call.', func.__name__)
        log = kwargs.get('log', logging.getLogger(func.__name__))
        try:
            ret = func(log=log, *args, **kwargs)
        finally:
            decorator_logger.debug('Leaving %s() function call.', func.__name__)
        return ret
    return wrapper
8750
def execstr_funckw(func):
    
    import utool as ut
    funckw = ut.get_func_kwargs(func)
    return ut.execstr_dict(funckw, explicit=True)
307366
def clock(logger):
    

    def decorator(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            _start = time.time()
            retval = func(*args, **kwargs)
            _end = time.time()
            logger.info('function {0} used : {1} s'.format(func.__name__, _end - _start))
            return retval

        return wrapper

    return decorator
535373
def call_func(self, *args, **kwargs):
        """"""
        asyncio.gather(
            self.cron(*args, **kwargs),
            loop=self.loop, return_exceptions=True
            ).add_done_callback(self.set_result)
418728
def wrap_context(func):
    
    @functools.wraps(func)
    def wrapper(self, request, context):
        return func(self, request, LogFieldsContext(context))

    return wrapper
862328
def avoid_parallel_execution(func):
    
    def func_wrapper(*args, **kwargs):
        if not getattr(func, "currently_executing", False):
            func.currently_executing = True
            try:
                return func(*args, **kwargs)
            finally:
                func.currently_executing = False
        else:
            logger.verbose("Avoid parallel execution of function {}".format(func))
    return func_wrapper
1340569
def _Function(self, t):
        
        if t.decorators is not None:
            self._fill("@")
            self._dispatch(t.decorators)
        self._fill("def "+t.name + "(")
        defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults)
        for i, arg in enumerate(zip(t.argnames, defaults)):
            self._write(arg[0])
            if arg[1] is not None:
                self._write('=')
                self._dispatch(arg[1])
            if i < len(t.argnames)-1:
                self._write(', ')
        self._write(")")
        if self._single_func:
            self._do_indent = False
        self._enter()
        self._dispatch(t.code)
        self._leave()
        self._do_indent = True
295103
def debug(func):
    
    @wraps(func)
    def wrapped(*args, **kwargs):
        arg = repr(args) + ' ' + repr(kwargs)
        sys.stdout.write('Entering ' + func.__name__ + arg + '\n')
        try:
            result = func(*args, **kwargs)
        except:
            sys.stdout.write('Traceback caught:\n')
            sys.stdout.write(format_exception(*sys.exc_info()))
            raise
        arg = repr(result)
        sys.stdout.write('Leaving ' + func.__name__ + '(): ' + arg + '\n')
        return result
    return wrapped
917401
def wrap_function(self, func):
        
        def f(*args, **kwds):
            # Start time
            timestamps = [_get_memory(os.getpid(), timestamps=True)]
            self.functions[func].append(timestamps)
            try:
                result = func(*args, **kwds)
            finally:
                # end time
                timestamps.append(_get_memory(os.getpid(), timestamps=True))
            return result
        return f
1082108
def _log(self,
             level,
             fmt,
             args=None,
             extra=None,
             exc_info=None,
             inc_stackinfo=False,
             inc_multiproc=False):
        
        if not self.enabled:
            return # Fail silently so that logging can easily be removed

        log_record = self._make_record(
          level, fmt, args, extra, exc_info, inc_stackinfo, inc_multiproc)

        logstr = log_record['defaultfmt'].format(**log_record) #whoah.

        if self.keep_history:
            self.history.append(logstr)

        log_funcs = self.config[level]
        to_remove = []
        for lf in log_funcs:
            try:
                lf.send(logstr)
            except StopIteration:
                # in the case that the log function is already closed, add it
                # to the list of functions to be deleted.
                to_remove.append(lf)
        for lf in to_remove:
            self.remove(level, lf)
            self.info('Logging function {} removed from level {}', lf, level)
705820
def job(func_or_queue=None, connection=None, *args, **kwargs):
    
    if callable(func_or_queue):
        func = func_or_queue
        queue = 'default'
    else:
        func = None
        queue = func_or_queue or 'default'

    if not isinstance(queue, basestring):
        queue = unicode(queue)

    try:
        queue = get_queue(queue)
        if connection is None:
            connection = queue.connection
    except KeyError:
        pass

    decorator = _job(queue, connection=connection, *args, **kwargs)
    if func:
        return decorator(func)
    return decorator
140651
def log_debug(func, *args, **kwargs):
    '''  '''
    logging.debug('Starting "%s" in thread %s...', func.__name__, current_thread())
    results = func(*args, **kwargs)
    logging.debug('Successfully finished "%s" in thread %s.', func.__name__, current_thread())
    return results
233790
def synchronise(func):
    
    def inner(request, *args):
        lock_id = '%s-%s-built-%s' % (
            datetime.date.today(), func.__name__,
            ",".join([str(a) for a in args]))

        if cache.add(lock_id, 'true', LOCK_EXPIRE):
            result = func(request, *args)
            cache.set(lock_id, result.task_id)
        else:
            task_id = cache.get(lock_id)
            if not task_id:
                return None

            cache.set(lock_id, "")
            result = Task.AsyncResult(task_id)
            if result.ready():
                result.forget()
                return None
        return result
    return inner
1004567
def trace(f):
    
    @functools.wraps(f)
    def decorator(*args, **kwargs):
        print 'Calling ' + f.func_name + ' in ' + str(args[0])
        return f(*args, **kwargs)
    return decorator