确定当前运行Python Cod的行的缩进级别

2024-05-16 10:16:07 发布

您现在位置:Python中文网/ 问答频道 /正文

在程序运行时,是否可以确定Python中一行的缩进级别?我希望能够根据正在运行的脚本的大纲结构来组织日志文件。在

在下面的示例中,“first message”函数将生成0,“second message”将为1,“third message”为2,“fourth,fifth,sixth”消息将为0

logger.debug('First message')
if True:
    logger.info('Second message')
    if True:
        logger.info('Third message')


logger.warning('Fourth message')
logger.error('Fifth message')
logger.critical('Sixth message')

相应的日志文件如下所示:

^{pr2}$

Tags: 文件函数info脚本程序运行true示例message
2条回答

首先,我检索调用者的代码上下文:

import inspect

context = inspect.getframeinfo(frame.f_back).code_context 

这给了我一个代码行的列表;除了第一行之外,我忽略了所有代码行。然后,我使用正则表达式来获取此行开头的空白;如果使用制表符,则必须先用适当数量的空格替换它们:

^{pr2}$

出于测试目的,我将空格替换为点,这样我就可以看到发生了什么,并构建了我的前缀:

white = "." * match.span(0)[1] # Change "." to " "!

{我现在可以使用CDlogger修改此消息:

^{4}$

如果我可以简单地用一个修饰符包装一个现有的记录器,将这个记录器转换成一个能识别空白的记录器,那就太好了。假设出于测试目的,我有一个非常原始的记录器,它只是将消息打印到stdout:

def pseudo_logger(msg):
    """Pseudo-logging function."""
    print(msg)

此记录器具有日志消息的第一个参数,可能还有一些其他位置参数和关键字。我想为这样一个函数编写一个装饰器:

from functools import wraps

def indented(func):
    """Turns the logger func(msg) into an indented logger."""
    @wraps(func)
    def wrapped(msg, *args, **kwargs):
        # ... compute white ...
        func(white + msg, *args, **kwargs)
    return wrapped

现在我可以得到一个新的记录器,例如:

new_logger = intented(pseudo_logger)

把它们放在一起可以得到:

from functools import wraps
import inspect
import re


def indented(func):
    """Turns the logger func(msg) into an indented logger."""
    indent = re.compile("^ *")    
    @wraps(func)
    def wrapped(msg, *args, **kwargs):
        frame = inspect.currentframe()
        context = inspect.getframeinfo(frame.f_back).code_context
        firstline = context[0]
        match = indent.match(firstline)
        white = "." * match.span(0)[1] # Change "." to " "!
        func(white + msg, *args, **kwargs)
    return wrapped

@indented
def pseudo_logger(msg):
    """Pseudo-logging function."""
    print(msg)

def main():
    pseudo_logger("This is an indented message!")
    if True:
        pseudo_logger("Another message, but more indented!")

    pseudo_logger("This "
                  "will ignore the indention of the second "
                  "or third line.")

if __name__ == "__main__":
    main()

不过,在生产代码中使用它,我会很犹豫。使用这样的代码检查是很脆弱的,并且根据您调用它的位置,它可能会导致意外的效果。在

我可以使用inspect.getouterframes()功能。这假设缩进使用4''字符而不是'\t'字符。在

import inspect

def getIndentationLevel():    

    # get information about the previous stack frame
    frame, filename, line_number,function_name, lines, index = inspect.getouterframes(inspect.currentframe())[1]

    # count the number of characters in the line
    original_length = len(lines[0])

    # trim the line of left spaces and record the new length
    new_length = len(lines[0].lstrip())

    # take the difference between the two values and divide by 4 to get the level number
    return int((original_length - new_length) / 4)

相关问题 更多 >