Move sys.stdout.encoding to top of function