import os, subprocess ITERATIONS = 5 def transform(line): return "ITERATIONS = " + str(int(line.split()[2]) - 1) + "\n" if line.startswith("ITERATIONS") else line with open(os.path.abspath(__file__), "r+") as f: new = ''.join(map(transform, f.readlines())) f.seek(0) f.write(new) if ITERATIONS > 1: print "iterations left: %s" % ITERATIONS print subprocess.Popen(["python", os.path.abspath(__file__)], stdout=subprocess.PIPE).communicate()[0], else: print "final iteration!"