Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d60f657

Browse files
committed
Add simple implementation of Python 3 style open()
1 parent cf41e14 commit d60f657

2 files changed

Lines changed: 29 additions & 5 deletions

File tree

IPython/core/magic.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
from IPython.core.prefilter import ESC_MAGIC
5353
from IPython.lib.pylabtools import mpl_runner
5454
from IPython.testing.skipdoctest import skip_doctest
55+
from IPython.utils import py3compat
5556
from IPython.utils.io import file_read, nlprint
5657
from IPython.utils.path import get_py_filename, unquote_filename
5758
from 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

IPython/utils/py3compat.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
"""Compatibility tricks for Python 3. Mainly to do with unicode."""
33
import sys
44

5+
orig_open = open
6+
57
def 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

4246
else:
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

6085
def execfile(fname, glob, loc=None):
6186
loc = loc if (loc is not None) else glob

0 commit comments

Comments
 (0)