在Python中检测缩进

时间:2019-04-13 21:32:44

标签: python

def divide(x, y): 
    try: 
        # Floor Division : Gives only Fractional Part as Answer 
        result = x // y 
        print("Yeah ! Your answer is :", result) 
    except ZeroDivisionError: 
        print("Sorry ! You are dividing by zero ")

    try: 
        result = x // y 
        print("Yeah ! Your answer is :", result) 
    except: 
        print("An error occurred") 

    try: 
        # Floor Division : Gives only Fractional Part as Answer 
        result = x // y 
        print("Yeah ! Your answer is :", result) 
    except ZeroDivisionError: 
        print("Sorry ! You are dividing by zero ")
    except NameError: 
        print("Name Error")
    except MemoryError: 
        print("Memory Error")
    except AttributeError: 
        print("Here is some\
            long long error message\
            .....")

我有一个具有三个try...except子句的函数。我的目标是检测它有多少个单独的try...except子句(此函数中为3个)以及每个子句中有多少个except关键字(第一个和第二个有1个,第三个有4个) )。

我尝试通过

导入此文件
with open("test.py", "r") as f:
    content = f.readlines()
    ... # getting each line

,并尝试通过检测缩进级别来划分try...except子句。 但是,我觉得这不是一种详尽的方法,可能会有更简单的方法。

有帮助吗?

1 个答案:

答案 0 :(得分:3)

为您的任务使用ast是一个起点。对于您的代码示例,它在第12行上毫无例外地检测到except并输出too broad except, line 12。我也用except Exception:进行了测试,消息是相同的,而使用except ZeroDivisionError: pass则消息是useless exception。您可以接受它并进一步改进(在模块中使用多个功能,等等)。

import ast

with open('test.py') as f:
    data = f.read()
    module = ast.parse(data)
    function = module.body[0]
    for obj in function.body:
        if isinstance(obj, ast.Try):
            try_block = obj
            for handler in try_block.handlers:
                if handler.type is None:
                    print('too broad except, line {}'.format(handler.lineno))
                    continue
                if handler.type == 'Exception':
                    print('too broad except, line {}'.format(handler.lineno))
                    continue
                if len(handler.body) == 1 and isinstance(handler.body[0], ast.Pass):
                    print('useless except, line {}'.format(handler.lineno))

对于问题中所述的目标(计数try...except块并计数except子句),这很容易,如您所见:len([obj for obj in function.body if isinstance(obj, ast.Try)])和{{1} }会做到的。