基于tmpl的批量python脚本生成

最近工作需要,需要根据输入的参数自动生成批量的python脚本。这些python脚本除了一些参数不同之外,其他内容都一样。

网上看到不少同志使用template模块来生成python脚本,于是自己也做了一些尝试。

1)首先需要先生成一个模板文件。命名为template.tmpl,如下。模板文件中使用${}括住的变量为需要传参进去修改的参数:

import sys

${A} is owned by youki
${B} is owned by kaiba
${C} is owned by maliku

2) 再定义一个python脚本,传入A|B|C的具体参数来生成实际的python脚本:

from string import Template
import sys
 
def build_tmpl(tmpl_filename, inst_filename, a, b, c):
    tmpl_file = open(tmpl_filename, 'r')
    tmpl = Template(tmpl_file.read())

    code_str = []
    code_str.append(tmpl.substitute(
        A = a,
        B = b,
        C = c
        ))
    
    inst_file = open(inst_filename, 'w')

    inst_file.writelines(code_str)
    inst_file.close()


if __name__ == '__main__':
    a_str = 'Osiris'
    b_str = 'Obelisk'
    c_str = 'La'
    template_file = './template.tmpl'
    output_file = 'test.py'
    build_tmpl(template_file, output_file, a_str, b_str, c_str)

具体逻辑如下:

  1. 读取template文件;
  2. 将template文件中的A,B,C分别替换为a,b,c
  3. 将替换后的文本写入实际的脚本文件中

3)最后生成的脚本文件如下:

import sys

Osiris is owned by youki
Obelisk is owned by kaiba
La is owned by maliku

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值