在Python中打印时包含当前方法名称

时间:2017-06-13 13:16:35

标签: python function debugging inspect

通常在C程序中(并使用GCC)我将创建一个包含当前函数名称的调试打印宏。就是这样:

#define DPRINTF(fmt, ...) printf("[%s] " fmt, __FUNCTION__, ##__VA_ARGS__)

使用时,当前函数将添加到每个打印前面,在运行时提供更有用的调试信息。例如,以下代码

#include <stdio.h>

#define DPRINT(fmt, ...) printf("[%s] " fmt, __FUNCTION__, ##__VA_ARGS__)

void testfunction1(){
    DPRINT("Running %d\n",1);
}

void testfunction2(){
    DPRINT("Running %d\n",2);
}

int main(void) {
    DPRINT("Running: %d\n",0);
    testfunction1();
    testfunction2();
    return 0;
}

输出:

[main] Running: 0
[testfunction1] Running 1
[testfunction2] Running 2

可以在Python中完成这样的事情吗?

我搜索了一下,发现了enter image description here StackOverflow问题,解释了如何使用inspect从堆栈中读取名称。但是,根据我发现Python不支持宏,因此不能使用与我的C程序相同的格式。

是否有某种机制可以支持这种类型的调试打印?我尝试了lambdas,但在这种情况下,“函数名称”打印为“&lt; lambda&gt;”。

3 个答案:

答案 0 :(得分:4)

您可以检查最后一帧以检索来电者姓名,其余的是简单格式,例如

 /**
        * Loads the required import and appends it to the document. It really doesn't
        * matter where it is appended.
        *
        **/
        function LoadImportAsync(href, elementName) {

            var link = document.createElement('link');
            link.rel = 'import';
            link.href = getBaseUrl() + "/NodeJS/Polymer/app/elements/" + href;
            link.setAttribute('async', ''); // make it async!
            link.onload = function () { Spinner(elementName, false); }
            link.onerror = function (e) { console.log("There was an error loading " + elementName + ". Please Check the URL") };
            document.head.appendChild(link);
        }

答案 1 :(得分:2)

我建议不要使用print,而是设置logger。日志记录模块的funcName属性可用于所有LogRecord

然后你会(代码取自zwer的答案):

import logging

def create_logger(app_name=None):
    logger = logging.getLogger(app_name or __name__)
    logger.setLevel(logging.DEBUG)
    log_format = '[%(asctime)-15s] [%(levelname)08s] (%(funcName)s %(message)s'
    logging.basicConfig(format=log_format)
    return logger

LOGGER = create_logger()

def testfunction1():
    LOGGER.info("Running %d", 1)

def testfunction2():
    LOGGER.error("Running %s", 2)

def main():
    LOGGER.debug("Running %03d", 0)
    testfunction1()
    testfunction2()

if __name__ == "__main__":
    main()

将生成类似于:

的内容
[2017-06-13 19:41:45,677] [   DEBUG] (main) Running 000
[2017-06-13 19:41:45,677] [    INFO] (testfunction1) Running 1
[2017-06-13 19:41:45,677] [   ERROR] (testfunction2) Running 2

答案 2 :(得分:1)

import inspect
import sys
def DPRINT(fmt, *args):
    print "{} {} {}".format(sys._getframe(1).f_code.co_name, fmt, args)

    # below line is another way to get the name of a calling function
    # print "{} {} {}".format(inspect.stack()[1][3], fmt, args)

def testfunction1():
    DPRINT("Running: 1")

def testfunction2():
    DPRINT("Running: 2")

def main():
    DPRINT("Running: 0")
    testfunction1()
    testfunction2()

main()

我不知道这是否有用