如何确定文件,功能和行号?

pen*_*gdu 53 python

在C++中,我可以像这样打印调试输出:

printf(
   "FILE: %s, FUNC: %s, LINE: %d, LOG: %s\n",
   __FILE__,
   __FUNCTION__,
   __LINE__,
   logmessage
);
Run Code Online (Sandbox Code Playgroud)

我怎样才能在Python中做类似的事情?

Tug*_*tes 67

有一个名为的模块inspect提供这些信息.

用法示例:

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()
Run Code Online (Sandbox Code Playgroud)

但是,请记住,有一种更简单的方法来获取当前正在执行的文件的名称:

print(__file__)
Run Code Online (Sandbox Code Playgroud)


Pre*_*gha 10

例如

import inspect
frame = inspect.currentframe()
# __FILE__
fileName  =  frame.f_code.co_filename
# __LINE__
fileNo = frame.f_lineno
Run Code Online (Sandbox Code Playgroud)

这里有更多http://docs.python.org/library/inspect.html


小智 10

你可以参考我的回答:https : //stackoverflow.com/a/45973480/1591700

import sys
print sys._getframe().f_lineno
Run Code Online (Sandbox Code Playgroud)

您还可以制作 lambda 函数


Mat*_*hew 8

以geowar的答案为基础:

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__()
Run Code Online (Sandbox Code Playgroud)

如果您通常想要__LINE__在例如print(或任何其他隐含str()或被repr()采用的时间)使用,上面将允许您省略()s.

(明显的扩展,将__call__左侧作为练习添加到读者.)


Hug*_*ins 7

哇,7岁的问题:)

无论如何,采用 ​​Tugrul 的答案,并将其编写为debug类型方法,它看起来像:

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()
Run Code Online (Sandbox Code Playgroud)

输出:

/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
Run Code Online (Sandbox Code Playgroud)


Chr*_*ker 6

我也对 python 中的 __LINE__ 命令感兴趣。我的起点是/sf/answers/476771431/,我用元类对象对其进行了扩展。通过这种修改,它具有与 C++ 相同的行为。

import inspect

class Meta(type):
    def __repr__(self):
        # Inspiration: /sf/answers/476771431/
        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
Run Code Online (Sandbox Code Playgroud)