【发布时间】:2010-10-16 01:42:12
【问题描述】:
本着现有"what's your most useful C/C++ snippet" 的精神 - 线程:
你们有没有(经常)使用的简短的、单功能的 Python sn-ps 并希望与 StackOverlow 社区分享?请保持条目小(25岁以下 行吗?),每篇文章只举一个例子。
我将从不时使用的简短 sn-p 开始计算 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)
【问题讨论】:
-
Python Cookbook (code.activestate.com/recipes/langs/python) 是一个更好的资源。示例、评论、cmets 以及在线和书籍形式提供。另外,您的示例是维护恐怖,并且 "%05d" % ln 比 "%s" % (str(len).zfill(5)) 好。
-
“恐怖”的示例:1) 如果 cur_path 为“/home/dalke”且 m 为“/home/dalke/subdir/home/dalke/”,则 m.split(curpath)[1] 失败任何”。 2) 不需要 list() 。 3) 'for b,zn in [(r,f) for ...]' 可以简化为 'for b,ignore,zn in os.walk(cur_path)。哦,还有 4) 换行和缩进有助于提高可读性
-
为什么不使用 .endswith() 来检查 .py 扩展名?
-
另外,建议使用一个集合作为忽略列表。这不是一个性能敏感的应用程序,但没有理由不利用哈希进行查找。
标签: python code-snippets