1 # Copyright (C) 2014-2016 Intel Corporation. All Rights Reserved.
3 # Permission is hereby granted, free of charge, to any person obtaining a
4 # copy of this software and associated documentation files (the "Software"),
5 # to deal in the Software without restriction, including without limitation
6 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
7 # and/or sell copies of the Software, and to permit persons to whom the
8 # Software is furnished to do so, subject to the following conditions:
10 # The above copyright notice and this permission notice (including the next
11 # paragraph) shall be included in all copies or substantial portions of the
14 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
17 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 from __future__
import print_function
27 from mako
.template
import Template
28 from mako
.exceptions
import RichTraceback
31 #==============================================================================
32 class MakoTemplateWriter
:
34 MakoTemplateWriter - Class (namespace) for functions to generate strings
35 or files using the Mako template module.
37 See http://docs.makotemplates.org/en/latest/ for
42 def to_string(template_filename
, **kwargs
):
44 Write template data to a string object and return the string
46 from mako
.template
import Template
47 from mako
.exceptions
import RichTraceback
50 template
= Template(filename
=template_filename
)
51 # Split + Join fixes line-endings for whatever platform you are using
52 return '\n'.join(template
.render(**kwargs
).splitlines())
54 traceback
= RichTraceback()
55 for (filename
, lineno
, function
, line
) in traceback
.traceback
:
56 print('File %s, line %s, in %s' % (filename
, lineno
, function
))
58 print('%s: %s' % (str(traceback
.error
.__class
__.__name
__), traceback
.error
))
61 def to_file(template_filename
, output_filename
, **kwargs
):
63 Write template data to a file
65 with
open(output_filename
, 'w') as outfile
:
66 print(MakoTemplateWriter
.to_string(template_filename
, **kwargs
), file=outfile
)
69 #==============================================================================
70 class ArgumentParser(argparse
.ArgumentParser
):
72 Subclass of argparse.ArgumentParser
74 Allow parsing from command files that start with @
78 Contents of myargs.txt:
82 The below function allows multiple args to be placed on the same text-file line.
83 The default is one token per line, which is a little cumbersome.
85 Also allow all characters after a '#' character to be ignored.
88 #==============================================================================
89 class _HelpFormatter(argparse
.RawTextHelpFormatter
):
90 ''' Better help formatter for argument parser '''
92 def _split_lines(self
, text
, width
):
93 ''' optimized split lines algorighm, indents split lines '''
94 lines
= text
.splitlines()
97 out_lines
.append(lines
[0])
98 for line
in lines
[1:]:
99 out_lines
.append(' ' + line
)
102 #==============================================================================
103 def __init__(self
, *args
, **kwargs
):
104 ''' Constructor. Compatible with argparse.ArgumentParser(),
105 but with some modifications for better usage and help display.
107 super(ArgumentParser
, self
).__init
__(
109 fromfile_prefix_chars
='@',
110 formatter_class
=ArgumentParser
._HelpFormatter
,
113 #==========================================================================
114 def convert_arg_line_to_args(self
, arg_line
):
115 ''' convert one line of parsed file to arguments '''
116 arg_line
= arg_line
.split('#', 1)[0]
117 if sys
.platform
== 'win32':
118 arg_line
= arg_line
.replace('\\', '\\\\')
119 for arg
in shlex
.split(arg_line
):
124 #==========================================================================
125 def _read_args_from_files(self
, arg_strings
):
126 ''' read arguments from files '''
127 # expand arguments referencing files
129 for arg_string
in arg_strings
:
131 # for regular arguments, just add them back into the list
132 if arg_string
[0] not in self
.fromfile_prefix_chars
:
133 new_arg_strings
.append(arg_string
)
135 # replace arguments referencing files with the file content
137 filename
= arg_string
[1:]
140 if not os
.path
.exists(filename
):
141 for path
in sys
.path
:
142 filename
= os
.path
.join(path
, arg_string
[1:])
143 if os
.path
.exists(filename
):
147 args_file
= open(filename
)
150 for arg_line
in args_file
.read().splitlines():
151 for arg
in self
.convert_arg_line_to_args(arg_line
):
152 arg_strings
.append(arg
)
153 arg_strings
= self
._read
_args
_from
_files
(arg_strings
)
154 new_arg_strings
.extend(arg_strings
)
158 err
= sys
.exc_info()[1]
161 # return the modified argument list
162 return new_arg_strings