对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 变量类型及命名规则介绍
Jun 08 Python
Python __setattr__、 __getattr__、 __delattr__、__call__用法示例
Mar 06 Python
Python 使用SMTP发送邮件的代码小结
Sep 21 Python
python批量替换页眉页脚实例代码
Jan 22 Python
python命令行解析之parse_known_args()函数和parse_args()使用区别介绍
Jan 24 Python
Python3中在Anaconda环境下安装basemap包
Oct 21 Python
对pandas的层次索引与取值的新方法详解
Nov 06 Python
python使用requests模块实现爬取电影天堂最新电影信息
Apr 03 Python
python将类似json的数据存储到MySQL中的实例
Jul 12 Python
Python使用matplotlib绘制三维参数曲线操作示例
Sep 10 Python
win10安装tesserocr配置 Python使用tesserocr识别字母数字验证码
Jan 16 Python
python使用建议与技巧分享(二)
Aug 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中date与gmdate的区别及默认时区设置
2014/05/12 PHP
PHP轻量级数据库操作类Medoo增加、删除、修改、查询例子
2014/07/04 PHP
PHP学习笔记(一) 简单了解PHP
2014/08/04 PHP
IIS下PHP的三种配置方式对比
2014/11/20 PHP
Web程序工作原理详解
2014/12/25 PHP
四种php中webservice实现的简单架构方法及实例
2015/02/03 PHP
nginx+thinkphp下解决不支持pathinfo模式
2015/07/01 PHP
wamp服务器访问php非常缓慢的解决过程
2015/07/01 PHP
WordPress用户登录框密码的隐藏与部分显示技巧
2015/12/31 PHP
PHP开发API接口签名生成及验证操作示例
2020/05/27 PHP
jQuery 页面 Mask实现代码
2010/01/09 Javascript
firefox下jQuery UI Autocomplete 1.8.*中文输入修正方法
2012/09/19 Javascript
js对列表中第一个值处理与jsp页面对列表中第一个值处理的区别详解
2013/11/05 Javascript
js propertychange和oninput事件
2014/09/28 Javascript
每天一篇javascript学习小结(RegExp对象)
2015/11/17 Javascript
深入理解javascript中concat方法
2016/12/12 Javascript
微信小程序 封装http请求实例详解
2017/01/16 Javascript
JS实现压缩上传图片base64长度功能
2019/12/03 Javascript
[39:00]Optic vs VP 2018国际邀请赛淘汰赛BO3 第三场 8.24
2018/08/25 DOTA
[01:02:07]Liquid vs Newbee 2019国际邀请赛小组赛 BO2 第一场 8.15
2019/08/16 DOTA
[01:01:41]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Magma BO3 第二场 1月31日
2021/03/11 DOTA
Python的Django中django-userena组件的简单使用教程
2015/05/30 Python
python爬虫获取多页天涯帖子
2018/02/23 Python
tensorflow 获取变量&打印权值的实例讲解
2018/06/14 Python
python selenium 弹出框处理的实现
2019/02/26 Python
python之列表推导式的用法
2019/11/29 Python
Python 获取命令行参数内容及参数个数的实例
2019/12/20 Python
英国标志性生活方式品牌:Skinnydip London
2019/12/15 全球购物
Lookfantastic澳大利亚官网:英国知名美妆购物网站
2021/01/07 全球购物
优秀生推荐信范文
2013/11/28 职场文书
女大学生自我鉴定
2013/12/09 职场文书
2014年党员公开承诺书范文
2014/03/28 职场文书
电子商务专业毕业生自荐书
2014/06/22 职场文书
教师群众路线剖析材料
2014/09/29 职场文书
初婚初育证明范本
2014/11/24 职场文书
碧霞祠导游词
2015/02/09 职场文书