diff --git a/hg b/hg
index 48572371d4785cdd75b5181c4ba3058d8df8e884_aGc=..40c956a683a44f5bc19e535f951b8ccab41ef49a_aGc= 100755
--- a/hg
+++ b/hg
@@ -12,6 +12,33 @@
 import os
 import sys
 
+# PYTHONLEGACYWINDOWSSTDIO=1 even when not defined
+if os.name == "nt" and "PYTHONLEGACYWINDOWSSTDIO" not in os.environ:
+    import io
+
+    # avoid deallocation
+    saved_stdin = sys.__stdin__
+    saved_stdout = sys.__stdout__
+    saved_stderr = sys.__stderr__
+
+    sys.stdin = io.TextIOWrapper(
+        io.FileIO(sys.stdin.fileno(), closefd=False), encoding="mbcs"
+    )
+    sys.stdout = io.TextIOWrapper(
+        io.FileIO(sys.stdout.fileno(), "wb", closefd=False),
+        encoding="mbcs",
+        errors="replace",
+    )
+    sys.stderr = io.TextIOWrapper(
+        io.FileIO(sys.stderr.fileno(), "wb", closefd=False),
+        encoding="mbcs",
+        errors="replace",
+    )
+
+    sys.__stdin__ = sys.stdin
+    sys.__stdout__ = sys.stdout
+    sys.__stderr__ = sys.stderr
+
 libdir = '@LIBDIR@'
 
 if libdir != '@' 'LIBDIR' '@':