python-3.x - Python 中的 __PRETTY_FUNCTION 等价物
问题描述
g++ 有一个很好的变量PRETTY_FUNCTION,它包含被调用函数的名称。对于函数,它产生原型(例如,“ void foo(long) ”)。对于类中的成员函数,名称包括类名(例如,“ void Foo::foo(long) ”)。
Python中是否有等价物。我一直在玩弄接近的“ sys._getframe() ”,但是当它是成员函数时,似乎没有类似的简单机制包括类名。
我喜欢在错误处理程序中使用它。
肯定有人对此有一个神奇的单线...
TIA,
-乔
解决方案
这是我现在能得到的最接近的。搜索“<<< 这里”。
键入 Foo。CLNAME有点傻。如果它可以以某种方式折叠到外部函数并留在类之外,那就太好了。必须有一种方法可以在 Python 中以类似于LINE和NAME的工作方式来执行此操作。
这两个的实现基于我从这里得到的代码:
好东西!
-乔
=====
#!/usr/bin/env python
# import system modules
#
import os
import sys
# define a hack to get the function name
#
class __MYNAME__(object):
def __repr__(self):
try:
raise Exception
except:
return str(sys.exc_info()[2].tb_frame.f_back.f_code.co_name)
def __init__(self):
pass
__NAME__ = __MYNAME__()
# define a hack to get the line number in a program
#
class __MYLINE__(object):
def __repr__(self):
try:
raise Exception
except:
return str(sys.exc_info()[2].tb_frame.f_back.f_lineno)
__LINE__ = __MYLINE__()
# use these in a function call
#
def joe():
print("[FUNCTION] name: %s, line: %s" %
(__NAME__, __LINE__)) # <<< here
# use these in a class member function
#
class Foo():
def __init__(self):
Foo.__CLNAME__ = self.__class__.__name__
def joe(self):
print("[CLASS] name: %s::%s, line: %s" %
(Foo.__CLNAME__, __NAME__, __LINE__)) # <<< here
#--------------------------------
# test all this in a main program
#--------------------------------
def main(argv):
# main program
#
print("[MAIN PROGRAM] name: %s, line: %s" %
(__NAME__, __LINE__)) # <<< here
# function call
#
joe()
# class member function
#
foo = Foo()
foo.joe()
# exit gracefully
#
sys.exit(os.EX_OK)
#
# end of main
# begin gracefully
#
if __name__ == "__main__":
main(sys.argv[0:])
#
# end of file
推荐阅读
- ssh - 有没有办法跨多个设备同步 ssh 目录密钥?
- sdn - 哪个 dpdk 版本适合 --- Intel Corporation "82541PI" (NIC) Gigabit Ethernet Controller (rev 05) 我在 ubuntu 18.04 上运行 dpdk
- apache-spark - 为什么火花重新分区会增加大小(数据量)
- html - 在 Bootstrap 3 中,如何每行只有五个图标?
- python - 如何更改matplotlib图的颜色条上大小的字体大小
- node.js - 无法让 NodeJS 将任何内容写入可写流
- python - 将 Google 搜索结果过滤为 Python 中的相关内容
- javascript - 我们可以在 a 上使用类吗