[1.7.x] Improved patching of sys.stdout in refs #23078.

Backport of 936fba5878 from master