Keine Beschreibung

automodify.py 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import os
  2. import sys
  3. import re
  4. import getopt
  5. import commands
  6. import subprocess
  7. import fnmatch
  8. import fileinput
  9. MATCH_FILE = ""
  10. TARGET_STRING = ""
  11. REPLACE_STRING = ""
  12. class color:
  13. PURPLE = '\033[95m'
  14. CYAN = '\033[96m'
  15. DARKCYAN = '\033[36m'
  16. BLUE = '\033[94m'
  17. GREEN = '\033[92m'
  18. YELLOW = '\033[93m'
  19. RED = '\033[91m'
  20. BOLD = '\033[1m'
  21. UNDERLINE = '\033[4m'
  22. END = '\033[0m'
  23. def showusage():
  24. print color.BOLD + "Usage:" + color.END
  25. print "python %s -m \'match_file\' -t \'target_string\' -r \'replace_string\'" % sys.argv[0]
  26. def getparamater(argv):
  27. try:
  28. opts, args = getopt.getopt(argv, "m:t:r:", ['match=target=replace='])
  29. return opts, args
  30. except getopt.GetoptError:
  31. showusage()
  32. sys.exit(1)
  33. def isparamatervalid():
  34. if len(MATCH_FILE) > 0 and len(TARGET_STRING) > 0 and len(REPLACE_STRING) > 0:
  35. return True
  36. return False
  37. def replace_match_filename_string(match_filename, oldstring, newstring):
  38. status, files = commands.getstatusoutput('find . -type f -name \'' + match_filename + '\'')
  39. for file in files.splitlines():
  40. replace_file_string(file, oldstring, newstring)
  41. def replace_file_string(filepath, oldstring, newstring):
  42. for line in fileinput.input(filepath, inplace = 1):
  43. sys.stdout.write(line.replace(oldstring, newstring))
  44. if __name__ == "__main__":
  45. opts, args = getparamater(sys.argv[1:])
  46. for opt, arg in opts:
  47. if opt in ("-m", "--match"):
  48. MATCH_FILE = arg
  49. if opt in ("-t", "--target"):
  50. TARGET_STRING = arg
  51. if opt in ("-r", "--replace"):
  52. REPLACE_STRING = arg
  53. if isparamatervalid():
  54. replace_match_filename_string(MATCH_FILE, TARGET_STRING, REPLACE_STRING)
  55. else:
  56. showusage()
  57. sys.exit(1)