# script.template
import network
from machine import Pin, PWM
from time import sleep
${xyz}
# script-generator.py
from string import Template
with open('script.template') as f:
template = Template(f.read()
contents = template.substitute(xyz='xyz')
with open('main.py', 'w') as f:
f.write(contents)
或者,如果一个单独的模板文件看起来像是过度杀戮,您也可以这样使用str.format():
script = """\
import network
from machine import Pin, PWM
from time import sleep
{xyz}
"""
data = {'xyz': 'xyz'}
with open('main.py', 'w') as f:
f.write(script.format(**data))
您可以将一个字符串附加到一个字符串,如下所示
您可以将脚本放入template中,然后填充值。如果生成的脚本相当复杂,那么这可能比连接字符串更容易管理。你知道吗
或者,如果一个单独的模板文件看起来像是过度杀戮,您也可以这样使用
str.format()
:相关问题 更多 >
编程相关推荐