1. import re
  2. import sys
  3. def replace_log_values(log_file_path, replacements):
  4. """
  5. Replaces values in a log file with specified replacements.
  6. Performs synchronous execution.
  7. Args:
  8. log_file_path (str): The path to the log file.
  9. replacements (dict): A dictionary where keys are the values to find
  10. and values are the replacements.
  11. """
  12. try:
  13. with open(log_file_path, 'r') as f:
  14. log_content = f.read()
  15. for find_str, replace_str in replacements.items():
  16. # Use re.escape to handle special characters in the find string
  17. pattern = re.escape(find_str)
  18. log_content = re.sub(pattern, replace_str, log_content)
  19. with open(log_file_path, 'w') as f:
  20. f.write(log_content)
  21. except FileNotFoundError:
  22. print(f"Error: File not found at {log_file_path}")
  23. sys.exit(1)
  24. except Exception as e:
  25. print(f"An error occurred: {e}")
  26. sys.exit(1)
  27. if __name__ == "__main__":
  28. # Example Usage:
  29. if len(sys.argv) != 3:
  30. print("Usage: python replace_values.py <log_file_path> <replacements_dict>")
  31. sys.exit(1)
  32. log_file_path = sys.argv[1]
  33. replacements_str = sys.argv[2]
  34. try:
  35. replacements = eval(replacements_str) # Evaluate the string as a dictionary
  36. except Exception as e:
  37. print(f"Error parsing replacements: {e}")
  38. sys.exit(1)
  39. replace_log_values(log_file_path, replacements)

Add your comment