Port to Python 3.
[catacomb-python] / pwsafe
diff --git a/pwsafe b/pwsafe
index dd46261..40a64ce 100644 (file)
--- a/pwsafe
+++ b/pwsafe
@@ -30,7 +30,7 @@
 from __future__ import with_statement
 
 from os import environ
-from sys import argv, exit, stdin, stdout, stderr
+import sys as SYS; from sys import argv, exit, stdin, stdout, stderr
 from getopt import getopt, GetoptError
 from fnmatch import fnmatch
 import re
@@ -41,8 +41,23 @@ from catacomb.pwsafe import *
 ###--------------------------------------------------------------------------
 ### Python version portability.
 
-def _text(bin): return bin
-def _bin(text): return text
+if SYS.version_info >= (3,):
+  import io as IO
+  def hack_stream(stream):
+    _enc = stream.encoding
+    _lbuf = stream.line_buffering
+    _nl = stream.newlines
+    return IO.TextIOWrapper(stream.detach(),
+                            encoding = _enc,
+                            line_buffering = _lbuf,
+                            newline = _nl,
+                            errors = "surrogateescape")
+  SYS.stdout = stdout = hack_stream(stdout)
+  def _text(bin): return bin.decode(errors = "surrogateescape")
+  def _bin(text): return text.encode(errors = "surrogateescape")
+else:
+  def _text(bin): return bin
+  def _bin(text): return text
 
 def _excval(): return SYS.exc_info()[1]