如何在Python中获得与C的__FUNCTION__相同的功能?

cod*_*nny 4 python function

在C中,我可以在这样的函数中放入一个log printf:

void xx_lock (int xx_flag)
{
  printf ("%s: START with %d\n", __FUNCTION__, xx_flag);
}
Run Code Online (Sandbox Code Playgroud)

所以我可以在任何函数中复制我需要的同一行,并在日志中显示函数名称.我想在Python中使用类似的东西.但是,如果我使用

__name__
Run Code Online (Sandbox Code Playgroud)

同样,它显示模块名称,而不是函数名称.

def xxx_lock(xx_flag=0)
    sys.stdout.write("%s: START with %d\n" % (__name__, xx_flag))
Run Code Online (Sandbox Code Playgroud)

是否有一些简单的构造可以在该示例中用于显示Python函数名称?要产生这样的输出:

xxx_lock: START with 1
Run Code Online (Sandbox Code Playgroud)

已编辑:已将参数添加到示例中.

Kat*_*iel 9

你所要求的是无法做到的(很好 - 有办法,但它们是讨厌的黑客).但是:你真的不想这样做.在更高层次上思考:您需要一种简单的方法来修改函数以记录它已经启动.更改函数的源代码不是一个好方法 - 毕竟,日志记录与函数正在做的事情无关!相反,您希望事后修改该功能.

def startLog( func ):
    def loggedFunc( *args, **kwargs ):
        print( "starting {0} with {1}".format( func.__name__, args[ 0 ] ) )
        return func( *args, **kwargs )

    return loggedFunc

@startLog
def theFunc( ):
    print( "running theFunc" )

theFunc( )
# starting theFunc
# running theFunc
Run Code Online (Sandbox Code Playgroud)

这是Python 装饰器的一个示例:它将define-time中的函数转换为另一个函数.这是语法糖:

def theFunc( ):
    print( "running theFunc" )
theFunc = startLog( theFunc )
Run Code Online (Sandbox Code Playgroud)

换句话说,你正在使用函数对象本身(记住 - 函数也是对象,你可以传递它们,修改它们,查看它们的属性等等)并重新定义它.查看源代码,我们看到startLog定义了一个新的函数(loggedFunc),它首先打印一个日志跟踪然后运行原始函数,并通过它的参数.运用装饰器替换theFuncloggedFunc,使绑定到名称的功能theFunc现在记录本身!

那有意义吗?我很乐意更详细地解释它.

编辑

正如已经指出的那样,这并没有具体回答你的问题; 如果你需要比这更多的功能,那么使用你需要的所有功能的logging模块,然后使用一些.走堆栈只是icky,以及脆弱,但= p.


loe*_*org 7

上面的katrielalex是对的,你不应该试图这样做"C路".Python包含电池,为什么不使用它们呢?

import logging, sys

logging.basicConfig(format="%(filename)s:%(funcName)s:%(message)s",level=logging.DEBUG,stream=sys.stderr)

def testFunc():
    logging.debug("entering")

testFunc()

  • @katriealex - 了解方向盘. (2认同)