How to determine file, function and line number?

前端 未结 7 1119
清歌不尽
清歌不尽 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

    Building on geowar's answer:

    class __LINE__(object):
        import sys
    
        def __repr__(self):
            try:
                raise Exception
            except:
                return str(sys.exc_info()[2].tb_frame.f_back.f_lineno)
    
    __LINE__ = __LINE__()
    

    If you normally want to use __LINE__ in e.g. print (or any other time an implicit str() or repr() is taken), the above will allow you to omit the ()s.

    (Obvious extension to add a __call__ left as an exercise to the reader.)

提交回复
热议问题