How to determine file, function and line number?

前端 未结 7 1123
清歌不尽
清歌不尽 2020-11-28 06:14

In C++, I can print debug output like this:

printf(
   \"FILE: %s, FUNC: %s, LINE: %d, LOG: %s\\n\",
   __FILE__,
   __FUNCTION__,
   __LINE__,
   logmessage         


        
7条回答
  •  再見小時候
    2020-11-28 07:02

    I was also interested in a __LINE__ command in python. My starting point was https://stackoverflow.com/a/6811020 and I extended it with a metaclass object. With this modification it has the same behavior like in C++.

    import inspect
    
    class Meta(type):
        def __repr__(self):
            # Inspiration: https://stackoverflow.com/a/6811020
            callerframerecord = inspect.stack()[1]  # 0 represents this line
            # 1 represents line at caller
            frame = callerframerecord[0]
            info = inspect.getframeinfo(frame)
            # print(info.filename)  # __FILE__     -> Test.py
            # print(info.function)  # __FUNCTION__ -> Main
            # print(info.lineno)  # __LINE__     -> 13
            return str(info.lineno)
    
    class __LINE__(metaclass=Meta):
        pass
    
    print(__LINE__)  # print for example 18
    

提交回复
热议问题