fill_template.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # /usr/bin/env python3
  2. from argparse import ArgumentParser
  3. from string import Template
  4. def split(string, delimiter):
  5. """Split a string using delimiter. Supports escaping.
  6. Args:
  7. string (str): The string to split.
  8. delimiter (str): The delimiter to split the string with.
  9. Returns:
  10. list: A list of strings.
  11. """
  12. result = []
  13. current = ""
  14. escape = False
  15. for char in string:
  16. if escape:
  17. current += char
  18. escape = False
  19. elif char == delimiter:
  20. result.append(current)
  21. current = ""
  22. elif char == "\\":
  23. escape = True
  24. else:
  25. current += char
  26. result.append(current)
  27. return result
  28. def main(file_path, substitutions, in_place):
  29. with open(file_path) as f:
  30. pbtxt = Template(f.read())
  31. sub_dict = {
  32. "max_queue_size": 0,
  33. 'max_queue_delay_microseconds': 0,
  34. }
  35. for sub in split(substitutions, ","):
  36. key, value = split(sub, ":")
  37. sub_dict[key] = value
  38. assert key in pbtxt.template, f"key '{key}' does not exist in the file {file_path}."
  39. pbtxt = pbtxt.safe_substitute(sub_dict)
  40. if in_place:
  41. with open(file_path, "w") as f:
  42. f.write(pbtxt)
  43. else:
  44. print(pbtxt)
  45. if __name__ == "__main__":
  46. parser = ArgumentParser()
  47. parser.add_argument("file_path", help="path of the .pbtxt to modify")
  48. parser.add_argument(
  49. "substitutions",
  50. help="substitutions to perform, in the format variable_name_1:value_1,variable_name_2:value_2..."
  51. )
  52. parser.add_argument("--in_place",
  53. "-i",
  54. action="store_true",
  55. help="do the operation in-place")
  56. args = parser.parse_args()
  57. main(**vars(args))