在Python中禁用断言 [英] Disable assertions in Python

查看:202
本文介绍了在Python中禁用断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Python中禁用断言?

How do I disable assertions in Python?

也就是说,如果断言失败,我不希望它抛出一个 AssertionError ,但要继续下去。

That is, if an assertion fails, I don't want it to throw an AssertionError, but to keep going.

我该怎么做?

推荐答案


如何在Python中禁用断言?


影响单一过程,环境或单行代码的方法。

There are multiple approaches that affect a single process, the environment, or a single line of code.

我演示每个。

使用 -O 标志(capital O)禁用进程中的所有assert语句。

Using the -O flag (capital O) disables all assert statements in a process.

例如:

$ python -Oc "assert False"

$ python -c "assert False"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AssertionError



对于环境



您可以使用环境变量来设置此标志。

For the environment

You can use an environment variable to set this flag as well.

这将影响使用或继承环境的每个进程。

This will affect every process that uses or inherits the environment.

例如,在Windows中,设置然后清除环境变量:

E.g., in Windows, setting and then clearing the environment variable:

C:\>python -c "assert False"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AssertionError
C:\>SET PYTHONOPTIMIZE=TRUE

C:\>python -c "assert False"

C:\>SET PYTHONOPTIMIZE=

C:\>python -c "assert False"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
AssertionError

在Unix中使用相同(使用set和设置

Same in Unix (using set and unset for respective functionality)

你继续你的问题:


如果断言失败,我不希望它抛出一个AssertionError,但要继续。

if an assertion fails, I don't want it to throw an AssertionError, but to keep going.

如果你想要的代码不成您可以发现断言​​错误:

If you want the code that fails to be exercised, you can catch an assertion error:

>>> try:
...     assert False, "we know this fails"
... except AssertionError as e:
...     print(repr(e))
...
AssertionError('we know this fails',)

你会继续从您处理 AssertionError

断言文档

这样的assert语句:

An assert statement like this:

assert expression #, optional_message

相当于

if __debug__:
    if not expression: raise AssertionError #(optional_message)

另外,


内置变量 __ debug __ True (请求优化时, False 选项 -O )。

the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O).

从用法文档:


-O

启用基本优化。这会将编译(字节码)文件的文件扩展名从.pyc更改为.pyo。另见PYTHONOPTIMIZE。

Turn on basic optimizations. This changes the filename extension for compiled (bytecode) files from .pyc to .pyo. See also PYTHONOPTIMIZE.


PYTHONOPTIMIZE

如果设置为非空字符串,则相当于
来指定 -O 选项。如果设置为整数,则相当于
多次指定 -O

If this is set to a non-empty string it is equivalent to specifying the -O option. If set to an integer, it is equivalent to specifying -O multiple times.

这篇关于在Python中禁用断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆