Utilities/compatibility_fixes.py

branch
Py2 comp.
changeset 2526
a91cba8291b9
child 2790
6686a3326df8
equal deleted inserted replaced
2525:8b507a9a2d40 2526:a91cba8291b9
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2013 Tobias Rzepka <tobias.rzepka@gmail.com>
4 #
5
6 """
7 Module implementing the open behavior of Python3 for use with Eric5.
8 The from Eric5 used features are emulated only. The not emulated features
9 should throw a NotImplementedError exception.
10 """
11
12 from __future__ import unicode_literals # __IGNORE_WARNING__
13
14 import __builtin__
15 import codecs
16
17
18 def open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True):
19 return File(file, mode, buffering, encoding, errors, newline, closefd)
20
21
22 class File(file):
23 def __init__(self, filein, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True):
24 self.__encoding = encoding
25 self.__newline = newline
26 self.__closefd = closefd
27 if newline is not None:
28 if 'r' in mode:
29 raise NotImplementedError
30 else:
31 mode = mode.replace('t', 'b')
32
33 if closefd == False:
34 raise NotImplementedError
35
36 if errors is None:
37 self.__errors = 'strict'
38 else:
39 self.__errors = errors
40
41 file.__init__(self, filein, mode, buffering)
42
43 def read(self, n=-1):
44 txt = super(File, self).read(n)
45 if self.__encoding is None:
46 return txt
47 else:
48 return codecs.decode(txt, self.__encoding)
49
50 def readline(self, limit=-1):
51 txt = super(File, self).readline(limit)
52 if self.__encoding is None:
53 return txt
54 else:
55 return codecs.decode(txt, self.__encoding)
56
57 def readlines(self, hint=-1):
58 if self.__encoding is None:
59 return super(File, self).readlines(hint)
60 else:
61 return [codecs.decode(txt, self.__encoding) for txt in super(File, self).readlines(hint)]
62
63 def write(self, txt):
64 if self.__encoding is not None:
65 txt = codecs.encode(txt, self.__encoding, self.__errors)
66
67 if self.__newline in ['\r\n', '\r']:
68 txt = txt.replace('\n', self.__newline)
69
70 super(File, self).write(txt)
71
72 def next(self):
73 txt = super(File, self).next()
74 if self.__encoding is None:
75 return txt
76 else:
77 return codecs.decode(txt, self.__encoding)
78
79
80 __builtin__.open = open
81
82 if __name__ == '__main__':
83 fp = open('compatibility_fixes.py', encoding='latin1')
84 print(fp.read())
85 fp.close()
86
87 with open('compatibility_fixes.py', encoding='UTF-8') as fp:
88 rlines = fp.readlines()
89 print(rlines[-1])

eric ide

mercurial