import argparse import sys import shutil from builtins import FileNotFoundError def main(argv): parser = argparse.ArgumentParser(description="Look for version number pattern in file and replace with autobuild version number") # Call once arguments to allow or disallow something parser.add_argument('-f', '--filetoconvert', help='The file to convert') parser.add_argument('-p', '--pattern', default='1.30000.0.0', help='The pattern to search for and replace') parser.add_argument('-s', '--substitute', help='The new version number that will substitute the pattern') args = parser.parse_args(argv) filetoconvert = args.filetoconvert pattern = args.pattern substitute = args.substitute print("Converting incidences of {0} with {1} in file: {2}\n".format(pattern, substitute, filetoconvert)) filecopy = filetoconvert + ".orig" try: shutil.move(filetoconvert, filecopy) except FileNotFoundError: print("Could not find file: {0}\n".format(filetoconvert)) return 1 with open(filetoconvert, 'x') as f: with open(filecopy,'r') as c: fileread = c.read() print("Detected %s instances of %s pre-conversion"%(fileread.count(pattern),pattern)) converted = fileread.replace(pattern, substitute) #print ("DEBUG: %s "%converted) print("Confirmed %s instances of %s post-conversion"%(converted.count(substitute),substitute)) f.write(converted) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))