portable.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #!/usr/bin/python
  2. from __future__ import print_function
  3. import sys
  4. import os
  5. import getopt
  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,
  33. "hf:s:r:",
  34. ["file=", "search=", "replace="])
  35. except getopt.GetoptError:
  36. display_help()
  37. for opt, arg in opts:
  38. if opt == '-h':
  39. display_help()
  40. elif opt in ("-f", "--file"):
  41. target = arg
  42. elif opt in ("-s", "--search"):
  43. search = arg
  44. elif opt in ("-r", "--replace"):
  45. replace = arg
  46. if target == '':
  47. display_help()
  48. if sys.version_info >= (3, 0):
  49. search = search.encode('utf-8')
  50. replace = replace.encode('utf-8')
  51. f = open(target, 'rb').read()
  52. f = f.replace(search, replace)
  53. f = f.replace(search.lower(), replace)
  54. open(target, 'wb').write(f)
  55. if __name__ == "__main__":
  56. main(sys.argv[1:])