File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 5252from IPython .core .prefilter import ESC_MAGIC
5353from IPython .lib .pylabtools import mpl_runner
5454from IPython .testing .skipdoctest import skip_doctest
55+ from IPython .utils import py3compat
5556from IPython .utils .io import file_read , nlprint
5657from IPython .utils .path import get_py_filename , unquote_filename
5758from IPython .utils .process import arg_split , abbrev_cwd
@@ -2085,11 +2086,9 @@ def magic_save(self,parameter_s = ''):
20852086 except (TypeError , ValueError ) as e :
20862087 print e .args [0 ]
20872088 return
2088- if isinstance (cmds , unicode ):
2089- cmds = cmds .encode ("utf-8" )
2090- with open (fname ,'w' ) as f :
2091- f .write ("# coding: utf-8\n " )
2092- f .write (cmds )
2089+ with py3compat .open (fname ,'w' , encoding = "utf-8" ) as f :
2090+ f .write (u"# coding: utf-8\n " )
2091+ f .write (py3compat .cast_unicode (cmds ))
20932092 print 'The following commands were written to file `%s`:' % fname
20942093 print cmds
20952094
Original file line number Diff line number Diff line change 22"""Compatibility tricks for Python 3. Mainly to do with unicode."""
33import sys
44
5+ orig_open = open
6+
57def no_code (x , encoding = None ):
68 return x
79
@@ -38,6 +40,8 @@ def isidentifier(s, dotted=False):
3840 if dotted :
3941 return all (isidentifier (a ) for a in s .split ("." ))
4042 return s .isidentifier ()
43+
44+ open = orig_open
4145
4246else :
4347 PY3 = False
@@ -56,6 +60,27 @@ def isidentifier(s, dotted=False):
5660 if dotted :
5761 return all (isidentifier (a ) for a in s .split ("." ))
5862 return bool (_name_re .match (s ))
63+
64+ class open (object ):
65+ """Wrapper providing key part of Python 3 open() interface."""
66+ def __init__ (self , fname , mode = "r" , encoding = "utf-8" ):
67+ self .f = orig_open (fname , mode )
68+ self .enc = encoding
69+
70+ def write (self , s ):
71+ return self .f .write (s .encode (self .enc ))
72+
73+ def read (self , size = - 1 ):
74+ return self .f .read (size ).decode (self .enc )
75+
76+ def close (self ):
77+ return self .f .close ()
78+
79+ def __enter__ (self ):
80+ return self
81+
82+ def __exit__ (self , etype , value , traceback ):
83+ self .f .close ()
5984
6085def execfile (fname , glob , loc = None ):
6186 loc = loc if (loc is not None ) else glob
You can’t perform that action at this time.
0 commit comments