对python实现模板生成脚本的方法详解


Posted in Python onJanuary 30, 2019

最近项目需要,针对主项目提取一个小的基础版本,供于在新建项目时使用,所以就有这个python模板生成脚本,其作用如下:

1、通过配置文件来控制模板中的数据、格式化的过滤条件

2、执行后会把目录下所有的文件都会执行一篇

#!/usr/bin/python
#encoding: utf-8
 
import json
import codecs
import os
 
def get_files(root_path):
  for dir in os.walk(root_path):
    if dir[2]:
      for nf in dir[2]:
        yield os.path.join(dir[0], nf)
 
def exclude_filter(exclude, nfile):
  files_path = exclude.get('file_path')
  files_name = exclude.get('file_name')
  base_name = os.path.basename(nfile)
  exts_name = exclude.get('ext_name')
  base_ext_name = base_name.rsplit(".", 1)[1]
  if files_path:
    for npath in files_path:
      if npath==nfile:
        return True
  elif files_name:
    for name in files_name:
      print name, base_name
      if name==base_name:
        return True
  elif exts_name:
    for name in exts_name:
      print name, base_ext_name
      if name==base_ext_name:
        return True
 
def include_filter(include, nfile):
  files_path = include.get('file_path')
  files_name = include.get('file_name')
  base_name = os.path.basename(nfile)
  if files_path:
    for npath in files_path:
      if npath==nfile:
        return True
  elif files_name:
    for name in files_name:
      if name==base_name:
        return True
 
def main():
  # read config
  config = {}
  with codecs.open("config.json","rb","UTF-8") as f:
    config = json.loads(f.read())
  if not config:
    return
 
  template = config.get("template")
  if template and template.get('path'):
    root_path = template.get('path')
    if not os.path.exists(root_path):
      print "source path not exist"
      return
    root_path = os.path.abspath(root_path)
    old_path = os.path.dirname(root_path)
  else:
    return
  exclude = template.get('exclude')
  include = template.get('include')
 
  store = config.get("store")
  if not store or not os.path.exists(store.get('dir_path', '')):
    return
 
  data = config.get("data")
  if not data:
    return
 
  if not os.path.exists(root_path):
    print 'root path not exists'
    return
 
  if os.path.isfile(root_path):
    files = [root_path]
  else:
    base_name = os.path.basename(root_path)
    store_root_path = os.path.join(store.get('dir_path'), base_name)
    if not os.path.exists(store_root_path):
      os.mkdir(store_root_path)
    files = get_files(root_path)
 
  for nfile in files:
    print nfile
    try:
      with codecs.open(nfile, "rb", "UTF-8") as f:
        s = f.read()
 
      if not exclude_filter(exclude, nfile) or include_filter(include, nfile):
        s = s % data
    except:
      with codecs.open(nfile, "rb") as f:
        s = f.read()
 
    # save to file
    fn = nfile.replace(old_path, store.get('dir_path'))
    fn_dir = os.path.dirname(fn)
    if not os.path.exists(fn_dir):
      os.makedirs(fn_dir)
    try:
      with codecs.open(fn, "wb", "UTF-8") as f:
        f.write(s)
        f.flush()
    except:
      with codecs.open(fn, "wb") as f:
        f.write(s)
        f.flush()
 
if __name__ == '__main__':
  main()

配置文件:

{
 "template": {
  "path" : "D:/tunicorn-web/framework-template",  ##模板文件主目录
  "exclude" : {                  ##不进行模板格式化的文件
   "file_path" : [],  
   "file_name" : ["config.json", "make_project.py"], 
   "ext_name" : ["css", "woff2"],
   "file_type" : [],
   "regex" : []
  },
  "include" : {                  ##进行模板格式化的文件
   "file_path" : [],
   "file_name" : []
  }
 },
 "store":{
  "dir_path" : "e:/test"             ##输出路径主目录     
  "data" : {
  "project_name":"NewJAVA",            ##模板数据
  "project_prefix":"newjava"           ##模板数据
 }
}

执行操作:

1、安装了python环境

2、双击python脚本

3、然后在执行下README中的步骤

readme:

README
=============

脚本使用
-------------
1. 打开config.json文件
2. 配置相关信息[输出目录、项目名称、项目前缀]
3. 执行make_project.py脚本
4. 查看输出目录

以上这篇对python实现模板生成脚本的方法详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python用字典统计单词或汉字词个数示例
Apr 22 Python
Python装饰器入门学习教程(九步学习)
Jan 28 Python
Python中%r和%s的详解及区别
Mar 16 Python
python+selenium打印当前页面的titl和url方法
Jun 22 Python
python绘制直线的方法
Jun 30 Python
python 实现返回一个列表中出现次数最多的元素方法
Jun 11 Python
如何在mac环境中用python处理protobuf
Dec 25 Python
tensorflow 报错unitialized value的解决方法
Feb 06 Python
Python关于反射的实例代码分享
Feb 20 Python
Python开发之pip安装及使用方法详解
Feb 21 Python
使用PyCharm安装pytest及requests的问题
Jul 31 Python
史上最详细的Python打包成exe文件教程
Jan 17 Python
ActiveMQ:使用Python访问ActiveMQ的方法
Jan 30 #Python
python 发送和接收ActiveMQ消息的实例
Jan 30 #Python
Python批量生成特定尺寸图片及图画任意文字的实例
Jan 30 #Python
理想高通滤波实现Python opencv示例
Jan 30 #Python
对DataFrame数据中的重复行,利用groupby累加合并的方法详解
Jan 30 #Python
WIn10+Anaconda环境下安装PyTorch(避坑指南)
Jan 30 #Python
对dataframe数据之间求补集的实例详解
Jan 30 #Python
You might like
php+oracle 分页类
2006/10/09 PHP
php异常处理方法实例汇总
2015/06/24 PHP
php 问卷调查结果统计
2015/10/08 PHP
php实现登录tplink WR882N获取IP和重启的方法
2016/07/20 PHP
PHP封装的PDO数据库操作类实例
2017/06/21 PHP
php实现socket推送技术的示例
2017/12/20 PHP
Laravel 错误提示本地化的实现
2019/10/22 PHP
可缩放Reloaded-一个针对可缩放元素的复用组件
2007/03/10 Javascript
用JSON做数据传输格式中的一些问题总结
2011/12/21 Javascript
推荐JavaScript实现继承的最佳方式
2014/11/11 Javascript
node.js中的buffer.Buffer.isEncoding方法使用说明
2014/12/14 Javascript
JavaScript实现将数组中所有元素连接成一个字符串的方法
2015/04/06 Javascript
jQuery插件扩展extend的简单实现原理
2016/06/24 Javascript
一个超简单的jQuery回调函数例子(分享)
2016/08/08 Javascript
jQuery 选择器(61种)整理总结
2016/09/26 Javascript
Angular页面间切换及传值的4种方法
2016/11/04 Javascript
Puppeteer 爬取动态生成的网页实战
2018/11/14 Javascript
微信小程序购物车、父子组件传值及calc的注意事项总结
2018/11/14 Javascript
JavaScript中的事件与异常捕获详析
2019/02/24 Javascript
JS+Canvas实现五子棋游戏
2020/08/26 Javascript
[54:28]EG vs OG 2019国际邀请赛小组赛 BO2 第一场 8.16
2019/08/18 DOTA
Python开发的单词频率统计工具wordsworth使用方法
2014/06/25 Python
python简单获取本机计算机名和IP地址的方法
2015/06/03 Python
python实现ID3决策树算法
2017/12/20 Python
对django后台admin下拉框进行过滤的实例
2019/07/26 Python
Python同时迭代多个序列的方法
2020/07/28 Python
Pycharm操作Git及GitHub的步骤详解
2020/10/27 Python
python温度转换华氏温度实现代码
2020/12/06 Python
某同学的自我鉴定范文
2013/12/26 职场文书
红旗方阵解说词
2014/02/12 职场文书
计算机专业自荐信范文
2014/05/28 职场文书
2015年保安个人工作总结
2015/04/02 职场文书
2015年三好一满意工作总结
2015/07/24 职场文书
三年级作文之趣事作文
2019/11/04 职场文书
mysql优化
2021/04/06 MySQL
Java 多线程并发FutureTask
2022/06/28 Java/Android