本着现有的“你最有用的 C/C++ 片段是什么”的精神- 线程:
你们有没有(经常)使用的简短的、单功能的 Python 代码片段并想与 StackOverlow 社区分享?请尽量减少条目(可能少于 25 行?),并且每篇文章只提供一个示例。
我将从一个我不时使用的简短片段开始计算 python 项目中的 sloc (源代码行):
# prints recursive count of lines of python source code from current directory
# includes an ignore_list. also prints total sloc
import os
cur_path = os.getcwd()
ignore_set = set(["__init__.py", "count_sourcelines.py"])
loclist = []
for pydir, _, pyfiles in os.walk(cur_path):
for pyfile in pyfiles:
if pyfile.endswith(".py") and pyfile not in ignore_set:
totalpath = os.path.join(pydir, pyfile)
loclist.append( ( len(open(totalpath, "r").read().splitlines()),
totalpath.split(cur_path)[1]) )
for linenumbercount, filename in loclist:
print "%05d lines in %s" % (linenumbercount, filename)
print "\nTotal: %s lines (%s)" %(sum([x[0] for x in loclist]), cur_path)