Skip to main content
 首页 » 编程设计

python之如何在未执行的代码中查找异常

2025年05月04日16bluestorm

在这个简单的 Python 代码中,如果 a 的值从 0 改变,那么将会有一个 NameError 显示 b 未定义。但是,如果从未执行 else 子句,则错误仍然隐藏。我怎样才能检测到这类错误?

a=0 
if a==0 : 
  print "hello" 
else : 
  print b 

请您参考如下方法:

pylint能够在不执行 python 代码的情况下找到很多常见(而不是很常见)的错误,示例输出:

C:  1, 0: Exactly one space required around assignment 
a=0 
 ^ (bad-whitespace) 
C:  2, 0: Exactly one space required around comparison 
if a==0 : 
    ^^ (bad-whitespace) 
C:  2, 0: No space allowed before : 
if a==0 : 
        ^ (bad-whitespace) 
C:  4, 0: No space allowed before : 
else : 
     ^ (bad-whitespace) 
C:  1, 0: Missing module docstring (missing-docstring) 
C:  1, 0: Invalid constant name "a" (invalid-name) 
E:  5,10: Undefined variable 'b' (undefined-variable) 

您在这里感兴趣的行是:E: 5,10: Undefined variable 'b' (undefined-variable)