制作Python代码Pythonic

0 python

你如何让代码更加Pythonic?

我想从/usr/local/sources/devel/algebra.py: def _alg(...)没有角色的样本中获取Paths :.

我的代码

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   
Run Code Online (Sandbox Code Playgroud)

[编辑]:只有内置函数才能以python方式编写代码.

Nad*_*mli 11

为什么不这样做:

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

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

import fileinput
for line in fileinput.input(paths):
    line = line.strip()
    if line.startswith('def '):
        print '%s: %s' % (fileinput.filename(), line.partition(':')[0])
Run Code Online (Sandbox Code Playgroud)

顺便说一下,如果你没有给fileinput.input任何路径它默认会使用sys.argv,所以你可以像这样运行你的python脚本:

$ python script.py filepath1 filepath2 filepath3
Run Code Online (Sandbox Code Playgroud)

fileinput将为您读取文件.

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

def func(): #comment myfunc():
   pass
Run Code Online (Sandbox Code Playgroud)

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

>>> 'def func(): #comment myfunc():'.partition(':')[0]
'def func()'
Run Code Online (Sandbox Code Playgroud)

除非你想要评论.