How to determine file, function and line number?

前端 未结 7 1074
清歌不尽
清歌不尽 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条回答
  • wow, 7 year old question :)

    Anyway, taking Tugrul's answer, and writing it as a debug type method, it can look something like:

    def debug(message):
        import sys
        import inspect
        callerframerecord = inspect.stack()[1]
        frame = callerframerecord[0]
        info = inspect.getframeinfo(frame)
        print(info.filename, 'func=%s' % info.function, 'line=%s:' % info.lineno, message)
    
    def somefunc():
        debug('inside some func')
    
    debug('this')
    debug('is a')
    debug('test message')
    somefunc()
    

    Output:

    /tmp/test2.py func=<module> line=12: this
    /tmp/test2.py func=<module> line=13: is a
    /tmp/test2.py func=<module> line=14: test message
    /tmp/test2.py func=somefunc line=10: inside some func
    
    0 讨论(0)
  • 2020-11-28 06:56

    For example

    import inspect
    frame = inspect.currentframe()
    # __FILE__
    fileName  =  frame.f_code.co_filename
    # __LINE__
    fileNo = frame.f_lineno
    

    There's more here http://docs.python.org/library/inspect.html

    0 讨论(0)
  • 2020-11-28 07:00

    There is a module named inspect which provides these information.

    Example usage:

    import inspect
    
    def PrintFrame():
      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
    
    def Main():
      PrintFrame()                              # for this line
    
    Main()
    

    However, please remember that there is an easier way to obtain the name of the currently executing file:

    print(__file__)
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-28 07:09

    You can refer my answer: https://stackoverflow.com/a/45973480/1591700

    import sys
    print sys._getframe().f_lineno
    

    You can also make lambda function

    0 讨论(0)
提交回复
热议问题