制作Python代码Pythonic

时间:2009-12-22 14:30:05

标签: python

你如何让代码更加Pythonic?

我希望将/usr/local/sources/devel/algebra.py: def _alg(...)中没有字符:的示例中的路径取出。

我的代码

import os
FunctionPath = "/usr/local/sources/devel/sage-main/build/sage/"
cmd = "grep -R 'def ' %s | cut -d' ' -f1" % (FunctionPath)
cmd += ' &'
raw_path = os.system(cmd)
path = raw_path.replace(':', '')       // not working

print path   

[edit]:代码只能通过内置函数进行pythonically 编写。

4 个答案:

答案 0 :(得分:11)

为什么不这样做:

for line in open(FunctionPath):
    line = line.strip()
    if line.startswith('def '):
        print '%s: %s' % (FunctionPath, line.partition(':')[0])

如果使用fileinput模块,您可以非常轻松地迭代多个输入流中的行:

import fileinput
for line in fileinput.input(paths):
    line = line.strip()
    if line.startswith('def '):
        print '%s: %s' % (fileinput.filename(), line.partition(':')[0])
顺便说一下,如果你没有给fileinput.input任何路径,它默认会使用sys.argv,所以你可以像这样运行你的python脚本:

$ python script.py filepath1 filepath2 filepath3

fileinput将为您读取文件。

如果你真的想要涵盖所有情况,你不应该使用替换(':',''),因为它可能有

def func(): #comment myfunc():
   pass

以下内容将为您提供正确的结果:

>>> 'def func(): #comment myfunc():'.partition(':')[0]
'def func()'

除非你想要评论。

答案 1 :(得分:1)

Literaly:“没有模块os,subprocess或Popen”

您还可以使用commands模块:P

答案 2 :(得分:1)

与os.walk相同

for path, dirnames, filenames in os.walk(function_path):
    for filename in filenames:
        path = os.path.join(path, filename)
        with open(path) as f:
             for line in f:
                 # Instead of grep
                 if 'def ' in line:
                       # Instead of cut
                       data = line.split(' ')[2]
                       print data.replace(":", '')

答案 3 :(得分:1)

如果您主要使用Python作为sh的包装器,为什么不直接从shell执行所有操作?

set SEARCH_PATH=/usr/local/sources/devel/sage-main/build/sage/
grep -R 'def ' $SEARCH_PATH | awk -F':' '{print $1 $2}'