对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 实现删除文件或文件夹实例详解
Dec 04 Python
利用Python脚本实现ping百度和google的方法
Jan 24 Python
Python部署web开发程序的几种方法
May 05 Python
python3.4实现邮件发送功能
May 28 Python
python中将zip压缩包转为gz.tar的方法
Oct 18 Python
python微信公众号之关注公众号自动回复
Oct 25 Python
Django通过dwebsocket实现websocket的例子
Nov 15 Python
python实现的Iou与Giou代码
Jan 18 Python
python json.dumps中文乱码问题解决
Apr 01 Python
Django后端分离 使用element-ui文件上传方式
Jul 12 Python
详解Python中的编码问题(encoding与decode、str与bytes)
Sep 30 Python
python基于tkinter制作无损音乐下载工具
Mar 29 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
mysql_fetch_assoc和mysql_fetch_row的功能加起来就是mysql_fetch_array
2007/01/15 PHP
php中DOMDocument简单用法示例代码(XML创建、添加、删除、修改)
2010/12/19 PHP
关于php curl获取301或302转向的网址问题的解决方法
2011/06/02 PHP
ThinkPHP实例化模型的四种方法概述
2014/08/22 PHP
windows中为php安装mongodb与memcache
2015/01/06 PHP
mod_php、FastCGI、PHP-FPM等PHP运行方式对比
2015/07/02 PHP
浅谈php错误提示及查错方法
2015/07/14 PHP
PHP与jquery实时显示网站在线人数实例详解
2016/12/02 PHP
Yii框架布局文件的动态切换操作示例
2019/11/11 PHP
如何通过Apache在本地配置多个虚拟主机
2020/07/29 PHP
js下用gb2312编码解码实现方法
2009/12/31 Javascript
详解addEventListener的三个参数之useCapture
2015/03/16 Javascript
jquery实现的省市区三级联动
2015/04/02 Javascript
javascript中this的四种用法
2015/05/11 Javascript
教你如何终止JQUERY的$.AJAX请求
2016/02/23 Javascript
Knockoutjs 学习系列(一)ko初体验
2016/06/07 Javascript
如何用js实现鼠标向上滚动时浮动导航
2016/07/18 Javascript
原生js实现键盘控制div移动且解决停顿问题
2016/12/05 Javascript
AngularJS基于ui-route实现深层路由的方法【路由嵌套】
2016/12/14 Javascript
使用vue实现点击按钮滑出面板的实现代码
2017/01/10 Javascript
JS简单获取当前日期和农历日期的方法
2017/04/17 Javascript
阿里大于短信验证码node koa2的实现代码(最新)
2017/09/07 Javascript
vue路由事件beforeRouteLeave及组件内定时器的清除方法
2018/09/29 Javascript
js实现延迟加载的几种方法详解
2019/01/19 Javascript
JavaScript两种计时器的实例讲解
2019/01/31 Javascript
微信小程序仿今日头条导航栏滚动解析
2019/08/20 Javascript
分析python服务器拒绝服务攻击代码
2014/01/16 Python
Tornado Web服务器多进程启动的2个方法
2014/08/04 Python
python的格式化输出(format,%)实例详解
2018/06/01 Python
Python urllib库如何添加headers过程解析
2020/10/05 Python
贷款担保申请书
2014/05/20 职场文书
积极向上的团队口号
2014/06/06 职场文书
贪污受贿检讨书范文
2014/11/19 职场文书
2014年班干部工作总结
2014/11/25 职场文书
工作经历证明范本
2015/06/15 职场文书
Mysql MVCC机制原理详解
2021/04/20 MySQL