portable.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3. import getopt
  4. import os
  5. import sys
  6. def display_help():
  7. print("####################################################################")
  8. print("# #")
  9. print("# File: portable.py #")
  10. print("# Description: #")
  11. print("# - search and replace within a binary file #")
  12. print("# #")
  13. print("# Parameters: #")
  14. print("# -f, --file : target file #")
  15. print("# -s, --search : term to search for #")
  16. print("# Default is the base path for the python #")
  17. print("# executable that is running this script. #")
  18. print("# In Py2 that would be C:\\Python27 #")
  19. print("# -r, --replace : replace with this #")
  20. print('# default is ".." #')
  21. print("# #")
  22. print("# example: #")
  23. print("# portable.py -f <target_file> -s <search_term> -r <replace_term> #")
  24. print("# #")
  25. print("####################################################################")
  26. sys.exit(2)
  27. def main(argv):
  28. target = ""
  29. search = os.path.dirname(sys.executable)
  30. replace = ".."
  31. try:
  32. opts, args = getopt.getopt(argv, "hf:s:r:", ["file=", "search=", "replace="])
  33. except getopt.GetoptError:
  34. display_help()
  35. for opt, arg in opts:
  36. if opt == "-h":
  37. display_help()
  38. elif opt in ("-f", "--file"):
  39. target = arg
  40. elif opt in ("-s", "--search"):
  41. search = arg
  42. elif opt in ("-r", "--replace"):
  43. replace = arg
  44. if target == "":
  45. display_help()
  46. if sys.version_info >= (3, 0):
  47. search = search.encode("utf-8")
  48. replace = replace.encode("utf-8")
  49. f = open(target, "rb").read()
  50. f = f.replace(search, replace)
  51. f = f.replace(search.lower(), replace)
  52. open(target, "wb").write(f)
  53. if __name__ == "__main__":
  54. main(sys.argv[1:])