@@ -550,11 +550,13 @@ def next_token(self):
550
550
self .token_kind = None
551
551
552
552
553
+ _default_line_directive = '// ###sourceLocation'
554
+
553
555
class ExecutionContext (object ):
554
556
555
557
"""State we pass around during execution of a template"""
556
558
557
- def __init__ (self , line_directive = '// ###sourceLocation' ,
559
+ def __init__ (self , line_directive = _default_line_directive ,
558
560
** local_bindings ):
559
561
self .local_bindings = local_bindings
560
562
self .line_directive = line_directive
@@ -744,6 +746,36 @@ def __str__(self, indent=''):
744
746
) + '\n ' + indent + '}'
745
747
return s + self .format_children (indent )
746
748
749
+ def expand (filename , line_directive = _default_line_directive , ** local_bindings ):
750
+ r"""Return the contents of the givepn template file, executed with the given
751
+ local bindings.
752
+
753
+ >>> from tempfile import NamedTemporaryFile
754
+ >>> f = NamedTemporaryFile()
755
+ >>> f.write(
756
+ ... '''---
757
+ ... % for i in range(int(x)):
758
+ ... a pox on ${i} for epoxy
759
+ ... % end
760
+ ... ''')
761
+ >>> f.flush()
762
+ >>> result = expand(
763
+ ... f.name, line_directive='//#sourceLocation', x=2
764
+ ... ).replace(
765
+ ... '"%s"' % f.name, '"dummy.file"')
766
+ >>> print(result, end='')
767
+ //#sourceLocation(file: "dummy.file", line: 1)
768
+ ---
769
+ //#sourceLocation(file: "dummy.file", line: 3)
770
+ a pox on 0 for epoxy
771
+ //#sourceLocation(file: "dummy.file", line: 3)
772
+ a pox on 1 for epoxy
773
+
774
+ """
775
+ with open (filename ) as f :
776
+ t = parse_template (filename , f .read ())
777
+ return execute_template (
778
+ t , line_directive = line_directive , ** local_bindings )
747
779
748
780
def parse_template (filename , text = None ):
749
781
r"""Return an AST corresponding to the given template file.
@@ -994,7 +1026,8 @@ def parse_template(filename, text=None):
994
1026
return Block (ParseContext (filename , text ))
995
1027
996
1028
997
- def execute_template (ast , line_directive = '' , ** local_bindings ):
1029
+ def execute_template (
1030
+ ast , line_directive = _default_line_directive , ** local_bindings ):
998
1031
r"""Return the text generated by executing the given template AST.
999
1032
1000
1033
Keyword arguments become local variable bindings in the execution context
@@ -1139,7 +1172,7 @@ def succ(a):
1139
1172
if args .test or args .verbose_test :
1140
1173
import doctest
1141
1174
selfmod = sys .modules [__name__ ]
1142
- if doctest .testmod (selfmod , verbose = args .verbose_test ).failed :
1175
+ if doctest .testmod (selfmod , verbose = args .verbose_test or None ).failed :
1143
1176
sys .exit (1 )
1144
1177
1145
1178
bindings = dict (x .split ('=' , 1 ) for x in args .defines )
0 commit comments