如何在函数内部将函数名称作为字符串打印在Python中

时间:2009-10-08 20:21:46

标签: python

def applejuice(q):
   print THE FUNCTION NAME!

它应该导致“applejuice”作为一个字符串。

7 个答案:

答案 0 :(得分:19)

这也有效:

import sys

def applejuice(q):
    func_name = sys._getframe().f_code.co_name
    print func_name

答案 1 :(得分:9)

def applejuice(**args):
    print "Running the function 'applejuice'"
    pass

或使用:

myfunc.__name__

>>> print applejuice.__name__
'applejuice'

另请参阅how-to-get-the-function-name-as-string-in-python

答案 2 :(得分:7)

import traceback

def applejuice(q):
   stack = traceback.extract_stack()
   (filename, line, procname, text) = stack[-1]
   print procname

我认为这用于调试,因此您可能希望查看traceback module提供的其他过程。它们将允许您打印整个调用堆栈,异常跟踪等。

答案 3 :(得分:3)

另一种方式

import inspect 
def applejuice(q):
    print inspect.getframeinfo(inspect.currentframe())[2]

答案 4 :(得分:2)

您需要解释您的问题所在。因为您的问题的答案是:

print "applejuice"

答案 5 :(得分:1)

这个网站给了我一个体面的解释,说明sys._getframe.f_code.co_name如何工作,返回函数名称。

http://code.activestate.com/recipes/66062-determining-current-function-name/

答案 6 :(得分:0)

def foo():
    # a func can just make a call to itself and fetch the name
    funcName = foo.__name__
    # print it
    print 'Internal: {0}'.format(funcName)
    # return it
    return funcName

# you can fetch the name externally
fooName = foo.__name__
print 'The name of {0} as fetched: {0}'.format(fooName)

# print what name foo returned in this example
whatIsTheName = foo()
print 'The name foo returned is: {0}'.format(whatIsTheName)