Skip to content

Instantly share code, notes, and snippets.

@luw2007
Created November 8, 2013 08:12
Show Gist options
  • Save luw2007/7367852 to your computer and use it in GitHub Desktop.
Save luw2007/7367852 to your computer and use it in GitHub Desktop.
diff --git a/pprint.py b/pprint.py
--- a/pprint.py
+++ b/pprint.py
@@ -36,6 +36,7 @@ saferepr()
import sys as _sys
import warnings
+import locale
from cStringIO import StringIO as _StringIO
@@ -247,14 +248,23 @@ class PrettyPrinter:
def _safe_repr(object, context, maxlevels, level):
typ = _type(object)
if typ is str:
+ string = object
+ string = string.replace('\n', '\\n').replace('\r','\\r').replace('\t','\\t')
if 'locale' not in _sys.modules:
return repr(object), True, False
if "'" in object and '"' not in object:
closure = '"'
quotes = {'"': '\\"'}
+ string = string.replace('"','\\"')
else:
closure = "'"
quotes = {"'": "\\'"}
+ string = string.replace("'", "\\'")
+ try:
+ string.decode('utf8').encode('gbk')
+ return ("%s%s%s" % (closure, string, closure)), True, False
+ except:
+ pass
qget = quotes.get
sio = _StringIO()
write = sio.write
@@ -265,6 +275,19 @@ def _safe_repr(object, context, maxlevel
write(qget(char, repr(char)[1:-1]))
return ("%s%s%s" % (closure, sio.getvalue(), closure)), True, False
+ if typ is unicode:
+ string = object.encode("utf8")
+ string = string.replace('\n', '\\n').replace('\r','\\r').replace('\t','\\t')
+ if "'" in object and '"' not in object:
+ closure = '"'
+ quotes = {'"': '\\"'}
+ string = string.replace('"','\\"')
+ else:
+ closure = "'"
+ quotes = {"'": "\\'"}
+ string = string.replace("'", "\\'")
+ return ("u%s%s%s" % (closure, string, closure)), True, False
+
r = getattr(typ, "__repr__", None)
if issubclass(typ, dict) and r is dict.__repr__:
if not object:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment