对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使用文件锁实现进程间同步功能【基于fcntl模块】
Oct 16 Python
解析Python中的eval()、exec()及其相关函数
Dec 20 Python
python操作mysql代码总结
Jun 01 Python
python3爬虫获取html内容及各属性值的方法
Dec 17 Python
python实现公司年会抽奖程序
Jan 22 Python
Scrapy框架爬取西刺代理网免费高匿代理的实现代码
Feb 22 Python
一步步教你用python的scrapy编写一个爬虫
Apr 17 Python
python读取.mat文件的数据及实例代码
Jul 12 Python
分享8点超级有用的Python编程建议(推荐)
Oct 13 Python
pyecharts动态轨迹图的实现示例
Apr 17 Python
Python加速程序运行的方法
Jul 29 Python
PyCharm2020.1.1与Python3.7.7的安装教程图文详解
Aug 07 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
深入解析fsockopen与pfsockopen的区别
2013/07/05 PHP
PHP echo,print,printf,sprintf函数之间的区别与用法详解
2013/11/27 PHP
php calender(日历)二个版本代码示例(解决2038问题)
2013/12/24 PHP
解密ThinkPHP3.1.2版本之模块和操作映射
2014/06/19 PHP
Laravel5框架自定义错误页面配置操作示例
2019/04/17 PHP
jquery+ashx无刷新GridView数据显示插件(实现分页、排序、过滤功能)
2010/04/25 Javascript
基于JavaScript实现百叶窗动画效果不只单纯flas可以实现
2016/02/29 Javascript
浅谈AngularJS中ng-class的使用方法
2016/11/11 Javascript
原生js实现键盘控制div移动且解决停顿问题
2016/12/05 Javascript
微信小程序 下拉菜单简单实例
2017/04/13 Javascript
jQuery操作之效果详解
2017/05/19 jQuery
jquery单击文字或图片内容放大并居中显示
2017/06/23 jQuery
解决Vue不能检测数组或对象变动的问题
2018/02/24 Javascript
实现Vue的markdown文档可以在线运行的方法示例
2018/12/11 Javascript
JavaScript数组、json对象、eval()函数用法实例分析
2019/02/21 Javascript
JavaScript设计模型Iterator实例解析
2020/01/22 Javascript
24个解决实际问题的ES6代码片段(小结)
2020/02/02 Javascript
[53:38]OG vs LGD 2018国际邀请赛淘汰赛BO3 第三场 8.26
2018/08/30 DOTA
[52:05]EG vs OG 2019国际邀请赛小组赛 BO2 第二场 8.16
2019/08/18 DOTA
python文件操作之目录遍历实例分析
2015/05/20 Python
Python的collections模块中的OrderedDict有序字典
2016/07/07 Python
PyQt5利用QPainter绘制各种图形的实例
2017/10/19 Python
基于Python的文件类型和字符串详解
2017/12/21 Python
Python基于OpenCV实现视频的人脸检测
2018/01/23 Python
对pandas通过索引提取dataframe的行方法详解
2019/02/01 Python
Python中判断子串存在的性能比较及分析总结
2019/06/23 Python
Python基础之函数原理与应用实例详解
2020/01/03 Python
在python中list作函数形参,防止被实参修改的实现方法
2020/06/05 Python
python快速安装OpenCV的步骤记录
2021/02/22 Python
英国户外装备和冒险服装零售商:alloutdoor
2018/01/30 全球购物
中秋寄语大全
2014/04/11 职场文书
工作保证书范文
2014/04/29 职场文书
会计个人实习计划书
2014/08/15 职场文书
2014幼儿园教育教学工作总结
2014/12/17 职场文书
2015年汽车销售经理工作总结
2015/04/27 职场文书
JavaScript前端面试组合函数
2022/06/21 Javascript