2009-10-08 63 views
8
def applejuice(q): 
    print THE FUNCTION NAME! 

它应该导致“applejuice”作为字符串。如何在函数内部以Python形式打印函数名称

+1

见http://meta.stackexchange.com/questions/18584/how-to-ask-a-smart-question-on-so/25128#25128 – 2009-10-08 20:39:20

+1

从您选择,我们可以将答案得出结论,这确实是重复的。事实上,一个几乎完全一样的问题已经存在:http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python – 2009-10-08 21:45:51

+0

我不同意这是一个#251464的重复 - 看起来这个问题是反过来的。 – 2012-11-10 19:09:08

回答

19

这也适用于:

import sys 

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

你需要解释你的问题是什么。因为回答你的问题是:

print "applejuice" 
+2

也许他的意思是:def func(anothah_func):打印anothah_func的名字 – wilhelmtell 2009-10-08 20:27:15

+0

嗯,那绝对有可能。我们会看看他是否说出了问题所在。 – 2009-10-08 20:38:36

7
import traceback 

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

我想这是用于调试,所以你可能想看看traceback module提供的其他程序。他们会告诉你打印整个调用堆栈,异常跟踪等

3

另一种方式

import inspect 
def applejuice(q): 
    print inspect.getframeinfo(inspect.currentframe())[2] 
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)