Python的断言assert
断言是用来判断是否让程序继续执行的一种辅助策略,可以提前阻止因为有些条件不满足而导致的程序崩溃。
断言的语法非常简单:assert express
如果experss为true, 程序继续执行,如果是false,则返回。
def divide(s): n = int(s) assert n != 0, 's should not be zero.' print('Going to divide 100 by {}'.format(s)) return 100 / n divide(0)
程序的输出为:
Traceback (most recent call last): File "/Users/xxx/PycharmProjects/netbarclient/httpproxy.py", line 8, in <module> divide(0) File "/Users/xxx/PycharmProjects/netbarclient/httpproxy.py", line 3, in divide assert n != 0, 's should not be zero.' AssertionError: s should not be zero. Process finished with exit code 1
如果在正式环境中关闭断言,方法是添加 -O 参数
python -O haproxy.py