我有 Python 代码,它尝试使用特殊语法 $[VARIABLE](注意方括号)和 string.template.safe_substitute() 替换变量。这工作正常,除了一个例外,当引用未定义的变量时,而不是单独留下引用,因为 safe_substitute() 记录了它用大括号替换方括号。模板中 RE 的高级使用没有详细记录(http://docs.python.org/2/library/string.html#template-strings),所以可能我只是用错了。想法?
这是测试用例的示例运行;请注意,定义 var 后一切正常:
% python tmpl.py
===$[UNDEFINED]===
===${UNDEFINED}===
% UNDEFINED=Hello python tmpl.py
===$[UNDEFINED]===
===Hello===
这是测试用例本身:
import os
from string import Template
# The strategy here is to replace $[FOO] but leave traditional
# shell-type expansions $FOO and ${FOO} alone.
# The '(?!)' below is a guaranteed-not-to-match RE.
class _Replace(Template):
pattern = r"""
\$(?:
(?P<escaped>(?!)) | # no escape char
(?P<named>(?!)) | # do not match $FOO, ${FOO}
\[(?P<braced>[A-Z_][A-Z_\d]+)\] | # do match $[FOO]
(?P<invalid>)
)
"""
if '__main__' == __name__:
text = '===$[UNDEFINED]==='
tmpl = _Replace(text)
result = tmpl.safe_substitute(os.environ)
print text
print result