Add sys.stdout.flush() in some places