gpt4 book ai didi

python - 在 Python 中检测缩进

转载 作者:太空宇宙 更新时间:2023-11-03 10:48:41 25 4
gpt4 key购买 nike

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 子句。但是,我觉得这并不是一种详尽无遗的方法,可能还有更简单的方法。

有什么帮助吗?

最佳答案

这是使用 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 block 并计算每个 block 中的 except 子句),这很容易,如您所见: len([obj for obj in function.body if isinstance(obj, ast.Try)])len(try_block.handlers) 将执行此操作。

关于python - 在 Python 中检测缩进,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55670056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com