简单的python宏扩展
smx的Python项目详细描述
简单的python模板
example:
- key : %os.environ.get(USER)
- roaming : %if(sys.platform=='win32',1,0)
%indent(%include(file_name))
- other : %eval(1 + 1)
%indent(%python("
import mod
f = open('myfile.in')
f.read()
output(mod.process(f))
")
允许以内联方式展开简单宏。您可以通过命令行from smx import Smx
进行计算。从命令行导入所有env变量或模块的选项都可用。宏可以嵌套…所以%expand(%include(...))
是一个有效的语法。
用于yml模板、配置文件、kubernate部署、简单的html页面等。
安装
pip install smx
使用
> smx file.in > file.out
> smx --help
或者来自python:
from smx import Smx
ctx = Smx()
ctx.expand("%add(1,1)")
ctx.expand_io(fin, fout)
ctx.expand_file(filename, in_place=True)
包括代码和文件
Macro | Description |
---|---|
indent(str) | each line of the indented string is indented at the level where the indent function was called. |
include(str) | include the specified file |
strip(str) | strip a string |
expand(str) | string is expanded using smx syntax |
python(str) | string is expanded using python syntax |
module(str) | string is interpreted as a module and imported |
模块
Macro | Description |
---|---|
os.... | os functions are included by default, for example ^{ |
sys.... | sys functions are included by default EG: ^{ |
其他
Macro | Description |
---|---|
for(name, range, loop) | loop code is expanded for each value in the range |
if(val, true-val, false-val) | if val is expanded to non-empty, true-val is executed |
add(a, b) | numbers are added |
sub(a, b) | numbers are subtracted |
目标
- 语法应该是“macroy”而不是“pythony”…这样你就可以知道,当宏正在运行的时候…与Python的较量。
- 通过从smx派生并使用@smx.macro decorator添加新函数,可以轻松添加自己的宏。
- 易于导入python模块并在基本上任何字符串上下文中使用它们
- json和yaml模板友好
- 在大多数配置上下文中使用“原样”
- 默认情况下是不安全的,但是使用“安全模式”允许不受信任地执行一组严格的宏扩展是微不足道的
注意事项
- 重要的是要记住,所有宏都会产生“字符串”,而不是其他python类型。
- 当面向上下文的模板编程变得复杂时,您可能不应该使用模板。