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

2024-09-26 17:57:43 发布

您现在位置:Python中文网/ 问答频道 /正文

根据python documentationassert,如果语句是用-O键编译的,那么它就不会包含在代码中。我想知道是否有可能用任意一段代码来模拟这种行为?你知道吗

例如,如果我有一个在执行期间被大量调用的记录器,那么我可以从消除if DEBUG: ...语句及其所有相关代码中获益。你知道吗


Tags: 代码debugif语句记录器documentationassert
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

如果没有任何附加注释,也很容易检测到这些内容。你知道吗

相关问题 更多 >

    热门问题