Skip to content

Commit

Permalink
Merge pull request #3 from timtan/issue-2-ipython-fix
Browse files Browse the repository at this point in the history
uniout now detects ipython and support ipython now
  • Loading branch information
moskytw committed Oct 5, 2013
2 parents 8f7fe0d + 4aaa302 commit 369d6a7
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 29 deletions.
31 changes: 31 additions & 0 deletions _uniout.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import re
import sys
# the helpers

escape_x_re = re.compile(r'(?:\\x[0-9a-f]{2})+')
escape_u_re = re.compile(r'(?:\\u[0-9a-f]{4}|\\U[0-9a-f]{8})+')
encoding = sys.getfilesystemencoding()

def dexuescape(s):
r'''decode the \x, \u and \U in a escaped string -> encoded string'''
s = escape_x_re.sub(lambda m: m.group().decode('string-escape'), s)
s = escape_u_re.sub(lambda m: m.group().decode('unicode-escape').encode(encoding), s)

# for Python < 2.7
if isinstance(s, unicode):
s = s.encode(encoding)

return s

# make uniout
uniout = lambda: 'middleware of stdout' # any instance

# make uniout look like stdout
for attrname in dir(sys.stdout):
if not attrname.startswith('__'):
setattr(uniout, attrname, getattr(sys.stdout, attrname))

# modify the write method to de-escape
uniout.write = lambda s: sys.__stdout__.write(dexuescape(s))

__all__ = ['uniout', 'dexuescape' ]
39 changes: 10 additions & 29 deletions uniout.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,36 +3,17 @@

__version__ = '0.2.2'

import re
import sys
from _uniout import uniout

# the helpers

escape_x_re = re.compile(r'(?:\\x[0-9a-f]{2})+')
escape_u_re = re.compile(r'(?:\\u[0-9a-f]{4}|\\U[0-9a-f]{8})+')
encoding = sys.getfilesystemencoding()
def runs_in_ipython():
import __builtin__
return '__IPYTHON__' in __builtin__.__dict__ and \
__builtin__.__dict__['__IPYTHON__']

def dexuescape(s):
r'''decode the \x, \u and \U in a escaped string -> encoded string'''
s = escape_x_re.sub(lambda m: m.group().decode('string-escape'), s)
s = escape_u_re.sub(lambda m: m.group().decode('unicode-escape').encode(encoding), s)

# for Python < 2.7
if isinstance(s, unicode):
s = s.encode(encoding)

return s

# make uniout
uniout = lambda: 'middleware of stdout' # any instance

# make uniout look like stdout
for attrname in dir(sys.stdout):
if not attrname.startswith('__'):
setattr(uniout, attrname, getattr(sys.stdout, attrname))

# modify the write method to de-escape
uniout.write = lambda s: sys.__stdout__.write(dexuescape(s))

# install the uniout
sys.stdout = uniout
if runs_in_ipython():
from IPython.utils import io
io.stdout = io.IOStream(uniout)
else:
sys.stdout = uniout

0 comments on commit 369d6a7

Please # to comment.