Improved patching of sys.stdout in refs #23078.