如何防止在Python中编译任意代码的一部分?

时间:2012-05-19 01:27:05

标签: python optimization assert

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

例如,如果我有一个在执行期间被大量调用的记录器,我可以从消除if DEBUG: ...语句中获益,并使用与它们相关的所有代码。

2 个答案:

答案 0 :(得分:2)

由于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

部分,在没有任何其他评论的情况下检测这些部分也很容易。

答案 1 :(得分:0)

为什么不注释掉你不想要#符号的代码呢?