递归遍历目录并替换函数调用 [英] Recursively traverse directory and replace function calls

查看:77
本文介绍了递归遍历目录并替换函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想递归遍历目录,并找到所有具有至少以下一组函数调用的文件:

I would like to traverse a directory recursively and find all files that have at least one of the function calls of the following set:

A(a)
B(a,b)
C(a,b,c)

现在,不考虑参数,我可以通过以下方式获取此类文件的列表

now, disregarding the arguments I can get a list of such files with

grep -r -l '[A-C](' .

尽管我确信我也可以以某种方式匹配参数.在这些文件上,我想执行以下操作:首先,我要备份,即将原始文件保存到filename.ext_bak或其他内容,而在filename.ext中,我要替换每次出现的函数调用

although I am sure I can also match the arguments somehow. On these files I want to do the following: First, I want a backup, i.e. save the original file to filename.ext_bak or something, whereas in the filename.ext I want to replace each occurence of the function call

X(a,...) 

作者

#ifdef LOL
   X_new(f(a),...)
#else
   X(a,...)
#endif

其中X可以是A,B,C,请注意X_new中的每个参数都包装在函数f(...)中. 将不胜感激!预先感谢!

where X can be A,B,C and notice that each argument in X_new is wrapped in a function f(...). Would appreciate any help! Thanks in advance!

推荐答案

此方法使用 os.walk 递归遍历所有文件(从当前工作目录开始).

This uses os.walk to traverse all files recursively (starting from the current working directory).

backup='_bak'参数告诉 fileinput.input 每个文件的备份.

The backup='_bak' argument tells fileinput.input to make a backup of each file.

import os
import sys
import re
import fileinput

def sub_callback(match):
    func,args=match.groups()
    fargs=','.join('f({a})'.format(a=a) for a in args.split(','))
    return ('''\
#if def LOL
    {func}_new({fa})        
#else
    {func}({a})
#endif
'''.format(func=func,a=args,fa=fargs))

for root, dirs, files in os.walk('.'):
    for line in fileinput.input(
        (os.path.join(root,name) for name in files),
        inplace=True,
        backup='_bak'
        ):
        line=re.sub(r'\b([A-C])\((.*?)\)',sub_callback,line)
        sys.stdout.write(line)

这篇关于递归遍历目录并替换函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆