[英]Detecting indentations in 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
子句。 但是,我覺得這不是一種詳盡的方法,而且可能有一種更簡單的方法。
有幫助嗎?
這是使用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)])
和len(try_block.handlers)
將做到這一點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.