繁体   English   中英

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

[英]How to print the function name as a string in Python from inside that function

def applejuice(q):
   print THE FUNCTION NAME!

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

这也有效:

import sys

def applejuice(q):
    func_name = sys._getframe().f_code.co_name
    print func_name
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

import traceback

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

我假设这用于调试,因此您可能希望查看traceback模块提供的其他过程。 它们可以让你打印整个调用堆栈,异常跟踪等。

其他方式

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

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

print "applejuice"

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM