对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 相关文章推荐
多线程爬虫批量下载pcgame图片url 保存为xml的实现代码
Jan 17 Python
在Python的Flask框架下使用sqlalchemy库的简单教程
Apr 09 Python
Django应用程序中如何发送电子邮件详解
Feb 04 Python
Python3 中文文件读写方法
Jan 23 Python
python-pyinstaller、打包后获取路径的实例
Jun 10 Python
用Pytorch训练CNN(数据集MNIST,使用GPU的方法)
Aug 19 Python
docker-py 用Python调用Docker接口的方法
Aug 30 Python
python用线性回归预测股票价格的实现代码
Sep 04 Python
Python Collatz序列实现过程解析
Oct 12 Python
python怎么调用自己的函数
Jul 01 Python
python控制台打印log输出重复的解决方法
May 14 Python
yolov5返回坐标的方法实例
Mar 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中通过ADO调用Access数据库的方法测试不通过
2006/12/31 PHP
php实现改变图片直接打开为下载的方法
2015/04/14 PHP
护卫神php套件 php版本升级方法(php5.5.24)
2015/05/10 PHP
php项目中百度 UEditor 简单安装调试和调用
2015/07/15 PHP
php时间计算相关问题小结
2016/05/09 PHP
验证token、回复图文\文本、推送消息的实用微信类php代码
2016/06/28 PHP
Nigma vs AM BO3 第二场2.13
2021/03/10 DOTA
身份证号码前六位所代表的省,市,区, 以及地区编码下载
2007/04/12 Javascript
强大的jquery插件jqeuryUI做网页对话框效果!简单
2011/04/14 Javascript
JavaScript起点(严格模式深度了解)
2013/01/28 Javascript
使用GruntJS构建Web程序之构建篇
2014/06/04 Javascript
从零学习node.js之文件操作(三)
2017/02/21 Javascript
javascript帧动画(实例讲解)
2017/09/02 Javascript
vue2.0获取鼠标位置的方法
2018/09/13 Javascript
mpvue+vuex搭建小程序详细教程(完整步骤)
2018/09/30 Javascript
vue实现div拖拽互换位置
2020/07/29 Javascript
浅谈实现在线预览PDF的几种解决办法
2020/08/10 Javascript
python 捕获 shell/bash 脚本的输出结果实例
2017/01/04 Python
详解Python中的Numpy、SciPy、MatPlotLib安装与配置
2017/11/17 Python
在Python中使用gRPC的方法示例
2018/08/08 Python
Python3实现统计单词表中每个字母出现频率的方法示例
2019/01/28 Python
Python实现查找字符串数组最长公共前缀示例
2019/03/27 Python
远程部署工具Fabric详解(支持Python3)
2019/07/04 Python
Python通过Tesseract库实现文字识别
2020/03/05 Python
python游戏开发的五个案例分享
2020/03/09 Python
python实现读取类别频数数据画水平条形图案例
2020/04/24 Python
世界上最大的糖果店:Dylan’s Candy Bar
2017/11/07 全球购物
英国布鲁姆精品店:Bloom Boutique
2018/03/01 全球购物
Under Armour安德玛法国官网:美国高端运动科技品牌
2018/06/29 全球购物
Spongelle官网:美国的创意护肤洗护品牌
2019/05/15 全球购物
JACK & JONES荷兰官网:男士服装和鞋子
2021/03/07 全球购物
办公室经理岗位职责
2014/01/01 职场文书
大学毕业感言200字
2014/03/09 职场文书
党的群众路线教育实践活动公开承诺书
2014/03/28 职场文书
小学大队长竞选稿
2015/11/20 职场文书
《最终幻想14》6.01版本4月5日推出 追加新任务新道具
2022/04/03 其他游戏