python - Python中如何防止部分任意代码被编译?

标签 python optimization assert

根据python documentation如果使用 -O 键编译代码,则 assert 语句不会包含在代码中。我想知道是否可以用任意一段代码来模拟这种行为?

例如,如果我有一个在执行过程中被大量调用的记录器,我可以从消除 if DEBUG: ... 语句及其关联的所有代码中受益。

最佳答案

由于Python是一种解释性语言,因此它不能在自己的代码中跳转。但您不需要“特殊工具”来删除部分代码——使用 Python!

这是一个最小的例子。您可能希望将 strip_debug() 函数放入 __init__.py 中,并让它处理模块列表。另外,您可能需要添加一些额外的检查,以确保用户确实想要修改代码,而不仅仅是运行代码。也许,使用像 --purge 这样的命令行选项会很好。然后,您可以复制您的库并运行一次

python __init__.py --purge

在您发布库或让用户自行决定之前。

#!/usr/bin/env python3.2

# BEGIN DEBUG
def _strip_debug():
    """
    Generates an optimized version of its own code stripping off all debugging
    code.

    """
    import os
    import re
    import shutil
    import sys
    import tempfile
    begin_debug = re.compile("^\s*#+\s*BEGIN\s+DEBUG\s*$")
    end_debug = re.compile("^\s*#+\s*END\s+DEBUG\s*$")
    tmp = None
    debug = False
    try:
        tmp = tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False)
        with open(sys.argv[0]) as my_code:
            for line in my_code:
                if begin_debug.match(line):
                    debug = True
                    continue
                elif end_debug.match(line):
                    debug = False
                    continue
                else:
                    if not debug:
                        tmp.write(line)
        tmp.close()
        shutil.copy(tmp.name, sys.argv[0])
    finally:
        os.unlink(tmp.name)
# END DEBUG    

def foo(bar, baz):
    """
    Do something weired with bar and baz.

    """
    # BEGIN DEBUG
    if DEBUG:
        print("bar = {}".format(bar))
        print("baz = {}".format(baz))
    # END DEBUG
    return bar + baz


# BEGIN DEBUG
if __name__ == "__main__":
    _strip_debug()
# END DEBUG

执行后,该文件将只包含foo()函数的功能代码。我已经使用了特殊注释

# BEGIN DEBUG

# END DEBUG

在此示例中,允许删除任意代码,但如果它只是为了删除

if DEBUG:
    # stuff

部分,在没有任何附加注释的情况下也很容易检测到这些部分。

关于python - Python中如何防止部分任意代码被编译?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10661578/

相关文章:

c++ - GCC 内联 C++ 函数是否没有 'inline' 关键字?

Java 数学运算符的相对性能

java - 在Java中断言一个集合有一个项目的多个实例?

java - 线程中的junit断言引发异常

python - 在嵌套的 Python 字典中搜索键

python - python 中嵌套元组的并行迭代

c# - "Cannot evaluate expression because the code of the current method is optimized."是什么意思?

arrays - Cypress 断言是数组中的元素

python - subprocess.check_output 不接受长参数

python - 如何在 pandas 中读取固定宽度格式的文本文件?