对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根据出生日期返回年龄的方法
Mar 26 Python
Python3实现简单可学习的手写体识别(实例讲解)
Oct 21 Python
Django基于ORM操作数据库的方法详解
Mar 27 Python
python获取酷狗音乐top500的下载地址 MP3格式
Apr 17 Python
对python 矩阵转置transpose的实例讲解
Apr 17 Python
Python实现通过继承覆盖方法示例
Jul 02 Python
django搭建项目配置环境和创建表过程详解
Jul 22 Python
python中property和setter装饰器用法
Dec 19 Python
Django模板标签中url使用详解(url跳转到指定页面)
Mar 19 Python
Python configparser模块操作代码实例
Jun 08 Python
Python可以用来做什么
Nov 23 Python
python代码实现图书管理系统
Nov 30 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 echo()和print()、require()和include()函数区别说明
2010/03/27 PHP
创建数据库php代码 用PHP写出自己的BLOG系统
2010/04/12 PHP
PHP实现文件下载断点续传详解
2014/10/15 PHP
php写入、删除与复制文件的方法
2015/06/20 PHP
php 计算两个时间相差的天数、小时数、分钟数、秒数详解及实例代码
2016/11/09 PHP
JavaScript库 开发规则
2009/01/31 Javascript
jquery.validate使用攻略 第二部
2010/07/01 Javascript
JS 控件事件小结
2012/10/31 Javascript
jQuery实现为LI列表前3行设置样式的方法【2种方法】
2016/09/04 Javascript
详解微信小程序开发之——wx.showToast(OBJECT)的使用
2017/01/18 Javascript
js学使用setTimeout实现轮循动画
2017/07/17 Javascript
Bootstrap 模态框多次显示后台提交多次BUG的解决方法
2017/12/26 Javascript
javaScript产生随机数的用法小结
2018/04/21 Javascript
基于vue.js组件实现分页效果
2018/12/29 Javascript
解决Layui数据表格显示无数据提示的问题
2019/11/14 Javascript
简单介绍利用TK在Python下进行GUI编程的教程
2015/04/13 Python
Python+matplotlib+numpy绘制精美的条形统计图
2018/01/02 Python
python实现机器人行走效果
2018/01/29 Python
Python管理Windows服务小脚本
2018/03/12 Python
Python输入二维数组方法
2018/04/13 Python
Pyqt5如何让QMessageBox按钮显示中文示例代码
2019/04/11 Python
详解Python的三种可变参数
2019/05/08 Python
使用Python实现毫秒级抢单功能
2019/06/06 Python
使用Pandas的Series方法绘制图像教程
2019/12/04 Python
如何解决cmd运行python提示不是内部命令
2020/07/01 Python
台湾屈臣氏网路商店:Watsons台湾
2020/12/29 全球购物
毕业生自荐书模版
2014/01/04 职场文书
学校安全工作制度
2014/01/19 职场文书
暑假家长评语大全
2014/04/17 职场文书
学校课外活动总结
2014/05/08 职场文书
品牌推广策划方案
2014/05/28 职场文书
岗位说明书怎么写
2014/07/30 职场文书
巾帼志愿者活动方案
2014/08/17 职场文书
邀请书格式范文
2015/02/02 职场文书
Python列表的索引与切片
2022/04/07 Python
使用Nginx的访问日志统计PV与UV
2022/05/06 Servers