Use the sys.stdout = open(outputfile, 'w') trick to write the generated output to the (optional) output file.