cmd.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # mako/cmd.py
  2. # Copyright (C) 2006-2016 the Mako authors and contributors <see AUTHORS file>
  3. #
  4. # This module is part of Mako and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. from argparse import ArgumentParser
  7. from os.path import isfile, dirname
  8. import sys
  9. from mako.template import Template
  10. from mako.lookup import TemplateLookup
  11. from mako import exceptions
  12. def varsplit(var):
  13. if "=" not in var:
  14. return (var, "")
  15. return var.split("=", 1)
  16. def _exit():
  17. sys.stderr.write(exceptions.text_error_template().render())
  18. sys.exit(1)
  19. def cmdline(argv=None):
  20. parser = ArgumentParser("usage: %prog [FILENAME]")
  21. parser.add_argument(
  22. "--var", default=[], action="append",
  23. help="variable (can be used multiple times, use name=value)")
  24. parser.add_argument(
  25. "--template-dir", default=[], action="append",
  26. help="Directory to use for template lookup (multiple "
  27. "directories may be provided). If not given then if the "
  28. "template is read from stdin, the value defaults to be "
  29. "the current directory, otherwise it defaults to be the "
  30. "parent directory of the file provided.")
  31. parser.add_argument('input', nargs='?', default='-')
  32. options = parser.parse_args(argv)
  33. if options.input == '-':
  34. lookup_dirs = options.template_dir or ["."]
  35. lookup = TemplateLookup(lookup_dirs)
  36. try:
  37. template = Template(sys.stdin.read(), lookup=lookup)
  38. except:
  39. _exit()
  40. else:
  41. filename = options.input
  42. if not isfile(filename):
  43. raise SystemExit("error: can't find %s" % filename)
  44. lookup_dirs = options.template_dir or [dirname(filename)]
  45. lookup = TemplateLookup(lookup_dirs)
  46. try:
  47. template = Template(filename=filename, lookup=lookup)
  48. except:
  49. _exit()
  50. kw = dict([varsplit(var) for var in options.var])
  51. try:
  52. print(template.render(**kw))
  53. except:
  54. _exit()
  55. if __name__ == "__main__":
  56. cmdline()