#!/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
为什么不把你不想要的代码注释掉?你知道吗
由于Python是一种解释语言,它不能在自己的代码中跳转。但是你不需要一个“特殊的工具”来剥离你的部分代码使用Python!你知道吗
这是一个最小的例子。您可能希望将
strip_debug()
函数放在__init__.py
中,让它处理模块列表。另外,您可能还需要添加一些额外的检查,以确保用户确实希望修改代码,而不仅仅是运行它。也许,使用命令行选项purge
会更好。然后,您可以复制一个库并运行一次在发布库之前,或者让用户自己发布。你知道吗
执行之后,这个文件将只包含
foo()
函数的函数代码。我用了特别的评论以及
在这个例子中,它允许剥离任意代码,但如果它只是为了删除
如果没有任何附加注释,也很容易检测到这些内容。你知道吗
相关问题 更多 >
编程相关推荐