Skip to main content
 首页 » 编程设计

python之为什么这是 Python 中的意外缩进

2025年05月04日14exmyth

#!/usr/bin/python 
 
try: 
    f = open("/home/masi/r.raw", "r+") 
    aBuf = f.seek(4)  
except: 
    print "Error at position : ", position 
 
events = [] 
for i in range(100): 
    aBuf = f.seek(4); 
 
    try: 
        if aBuf[:4] == b'\xFA\xFA\xFA\xFA': 
            print("E") 
 
    except: 
    #   print "\0" 
 
f.close() 

当我注释掉 except 的打印时,出现错误

    f.close() 
    ^ 
IndentationError: expected an indented block 

我认为我需要 try-except,因为 if 子句经常为假。

为什么会出现这种意外的缩进?

请您参考如下方法:

except 需要一个或多个语句。

你可以这样写:

try: 
    if aBuf[:4] == b'\xFA\xFA\xFA\xFA': 
        print("E") 
except: 
    pass 

警告
如评论中所述,使用 except: pass 不是一个好习惯。
参见 Why is “except: pass” a bad programming practice? .