##// END OF EJS Templates
Add simple implementation of Python 3 style open()
Thomas Kluyver -
Show More

The requested changes are too big and content was truncated. Show full diff

1 NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,62 +1,87 b''
1 1 # coding: utf-8
2 2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 3 import sys
4 4
5 orig_open = open
6
5 7 def no_code(x, encoding=None):
6 8 return x
7 9
8 10 def decode(s, encoding=None):
9 11 encoding = encoding or sys.stdin.encoding or sys.getdefaultencoding()
10 12 return s.decode(encoding, "replace")
11 13
12 14 def encode(u, encoding=None):
13 15 encoding = encoding or sys.stdin.encoding or sys.getdefaultencoding()
14 16 return u.encode(encoding, "replace")
15 17
16 18 def cast_unicode(s, encoding=None):
17 19 if isinstance(s, bytes):
18 20 return decode(s, encoding)
19 21 return s
20 22
21 23 def cast_bytes(s, encoding=None):
22 24 if not isinstance(s, bytes):
23 25 return encode(s, encoding)
24 26 return s
25 27
26 28 if sys.version_info[0] >= 3:
27 29 PY3 = True
28 30
29 31 input = input
30 32 builtin_mod_name = "builtins"
31 33
32 34 str_to_unicode = no_code
33 35 unicode_to_str = no_code
34 36 str_to_bytes = encode
35 37 bytes_to_str = decode
36 38
37 39 def isidentifier(s, dotted=False):
38 40 if dotted:
39 41 return all(isidentifier(a) for a in s.split("."))
40 42 return s.isidentifier()
43
44 open = orig_open
41 45
42 46 else:
43 47 PY3 = False
44 48
45 49 input = raw_input
46 50 builtin_mod_name = "__builtin__"
47 51
48 52 str_to_unicode = decode
49 53 unicode_to_str = encode
50 54 str_to_bytes = no_code
51 55 bytes_to_str = no_code
52 56
53 57 import re
54 58 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
55 59 def isidentifier(s, dotted=False):
56 60 if dotted:
57 61 return all(isidentifier(a) for a in s.split("."))
58 62 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()
59 84
60 85 def execfile(fname, glob, loc=None):
61 86 loc = loc if (loc is not None) else glob
62 87 exec compile(open(fname).read(), fname, 'exec') in glob, loc
General Comments 0
You need to be logged in to leave comments. Login now