/
_compat.py
361 lines (303 loc) · 11.1 KB
/
_compat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import sys
import codecs
import re
python_version = sys.version_info[0]
try:
from json import loads, dumps, JSONEncoder
except ImportError:
from simplejson import loads, dumps, JSONEncoder
try:
from urllib.parse import quote
except ImportError:
from urllib import quote
try:
from html import escape
except ImportError:
from cgi import escape
try:
from socketserver import TCPServer
except ImportError:
from SocketServer import TCPServer
if python_version == 2:
from StringIO import StringIO
else:
from io import StringIO
if python_version == 2:
def execute(cmd, globals_, locals_):
exec('exec cmd in globals_, locals_')
else:
def execute(cmd, globals_, locals_):
exec(cmd, globals_, locals_)
_cookie_search = re.compile("coding[:=]\s*([-\w.]+)").search
def _detect_encoding(filename):
import linecache
lines = linecache.getlines(filename)
return _detect_lines_encoding(lines)
def _detect_lines_encoding(lines):
if not lines or lines[0].startswith(u("\xef\xbb\xbf")):
return "utf-8"
magic = _cookie_search("".join(lines[:2]))
if magic is None:
return 'utf-8'
encoding = magic.group(1)
try:
codecs.lookup(encoding)
except LookupError:
return 'utf-8'
return encoding
if python_version == 2:
basestr = basestring
def to_unicode(string):
return string.decode('utf-8')
def to_unicode_string(string, filename):
if isinstance(string, unicode):
return string
encoding = _detect_encoding(filename)
if encoding != 'utf-8' and string:
return string.decode(encoding).encode('utf-8')
else:
return string
def to_bytes(string):
return string
def from_bytes(bytes_):
return bytes_
def force_bytes(bytes_):
if isinstance(bytes_, unicode):
return bytes_.encode('utf-8')
return bytes_
else:
basestr = (str, bytes)
def to_unicode(string):
return string
def to_unicode_string(string, filename):
return string
def to_bytes(string):
return string.encode('utf-8')
def from_bytes(bytes_):
return bytes_.decode('utf-8')
def force_bytes(bytes_):
if isinstance(bytes_, str):
return bytes_.encode('utf-8')
return bytes_
def is_str(string):
return isinstance(string, basestr)
def u(s):
if python_version == 2:
return s.decode('utf-8')
return s
if python_version == 2:
import struct
import socket
import errno
import time
import select
if sys.platform == 'win32':
from _winapi import WAIT_OBJECT_0, WAIT_TIMEOUT, INFINITE
import _winapi
def _exhaustive_wait(handles, timeout):
# Return ALL handles which are currently signalled. (Only
# returning the first signalled might create starvation issues.)
L = list(handles)
ready = []
while L:
res = _winapi.WaitForMultipleObjects(L, False, timeout)
if res == WAIT_TIMEOUT:
break
elif WAIT_OBJECT_0 <= res < WAIT_OBJECT_0 + len(L):
res -= WAIT_OBJECT_0
elif WAIT_ABANDONED_0 <= res < WAIT_ABANDONED_0 + len(L):
res -= WAIT_ABANDONED_0
else:
raise RuntimeError('Should not get here')
ready.append(L[res])
L = L[res+1:]
timeout = 0
return ready
_ready_errors = {
_winapi.ERROR_BROKEN_PIPE, _winapi.ERROR_NETNAME_DELETED}
def wait(object_list, timeout=None):
'''
Wait till an object in object_list is ready/readable.
Returns list of those objects in object_list which are
ready/readable.
'''
if timeout is None:
timeout = INFINITE
elif timeout < 0:
timeout = 0
else:
timeout = int(timeout * 1000 + 0.5)
object_list = list(object_list)
waithandle_to_obj = {}
ov_list = []
ready_objects = set()
ready_handles = set()
try:
for o in object_list:
try:
fileno = getattr(o, 'fileno')
except AttributeError:
waithandle_to_obj[o.__index__()] = o
else:
# start an overlapped read of length zero
try:
ov, err = _winapi.ReadFile(fileno(), 0, True)
except OSError as e:
err = e.winerror
if err not in _ready_errors:
raise
if err == _winapi.ERROR_IO_PENDING:
ov_list.append(ov)
waithandle_to_obj[ov.event] = o
else:
# If o.fileno() is an overlapped pipe handle and
# err == 0 then there is a zero length message
# in the pipe, but it HAS NOT been consumed.
ready_objects.add(o)
timeout = 0
ready_handles = _exhaustive_wait(
waithandle_to_obj.keys(), timeout)
finally:
# request that overlapped reads stop
for ov in ov_list:
ov.cancel()
# wait for all overlapped reads to stop
for ov in ov_list:
try:
_, err = ov.GetOverlappedResult(True)
except OSError as e:
err = e.winerror
if err not in _ready_errors:
raise
if err != _winapi.ERROR_OPERATION_ABORTED:
o = waithandle_to_obj[ov.event]
ready_objects.add(o)
if err == 0:
# If o.fileno() is an overlapped pipe handle then
# a zero length message HAS been consumed.
if hasattr(o, '_got_empty_message'):
o._got_empty_message = True
ready_objects.update(waithandle_to_obj[h] for h in ready_handles)
return [o for o in object_list if o in ready_objects]
else:
if hasattr(select, 'poll'):
def _poll(fds, timeout):
if timeout is not None:
timeout = int(timeout * 1000) # timeout is in milliseconds
fd_map = {}
pollster = select.poll()
for fd in fds:
pollster.register(fd, select.POLLIN)
if hasattr(fd, 'fileno'):
fd_map[fd.fileno()] = fd
else:
fd_map[fd] = fd
ls = []
for fd, event in pollster.poll(timeout):
if event & select.POLLNVAL:
raise ValueError('invalid file descriptor %i' % fd)
ls.append(fd_map[fd])
return ls
else:
def _poll(fds, timeout):
return select.select(fds, [], [], timeout)[0]
def wait(object_list, timeout=None):
'''
Wait till an object in object_list is ready/readable.
Returns list of those objects in object_list which are ready/readable.
'''
if timeout is not None:
if timeout <= 0:
return _poll(object_list, 0)
else:
deadline = time.time() + timeout
while True:
try:
return _poll(object_list, timeout)
except OSError as e:
if e.errno != errno.EINTR:
raise
if timeout is not None:
timeout = deadline - time.time()
class Socket(object):
"""A Socket compatible with multiprocessing.connection.Client, that
uses socket objects."""
# https://github.com/akheron/cpython/blob/3.3/Lib/multiprocessing/connection.py#L349
def __init__(self, address):
self._handle = socket.socket()
self._handle.connect(address)
self._handle.setblocking(1)
def send_bytes(self, buf):
self._check_closed()
n = len(buf)
# For wire compatibility with 3.2 and lower
header = struct.pack("!i", n)
if n > 16384:
# The payload is large so Nagle's algorithm won't be triggered
# and we'd better avoid the cost of concatenation.
chunks = [header, buf]
elif n > 0:
# Issue #20540: concatenate before sending, to avoid delays
# dueto Nagle's algorithm on a TCP socket.
chunks = [header + buf]
else:
# This code path is necessary to avoid "broken pipe" errors
# when sending a 0-length buffer if the other end closed the
# pipe.
chunks = [header]
for chunk in chunks:
self._handle.sendall(chunk)
def _safe_recv(self, *args, **kwargs):
while True:
try:
return self._handle.recv(*args, **kwargs)
except socket.error as e:
# Interrupted system call
if e.errno != errno.EINTR:
raise
def recv_bytes(self):
self._check_closed()
size, = struct.unpack("!i", self._safe_recv(4))
return self._safe_recv(size)
def _check_closed(self):
if self._handle is None:
raise IOError("handle is closed")
def close(self):
self._check_closed()
self._handle.close()
self._handle = None
def poll(self, timeout=0.0):
"""Whether there is any input available to be read"""
self._check_closed()
return self._poll(timeout)
def _poll(self, timeout):
r = wait([self._handle], timeout)
return bool(r)
else:
from multiprocessing.connection import Client as Socket
try:
from importlib.util import find_spec
from importlib import import_module
def existing_module(module):
return bool(find_spec(module))
except ImportError:
import imp
def existing_module(module):
try:
imp.find_module(module)
return True
except ImportError:
return False
def import_module(module):
__import__(module)
if module not in sys.modules:
raise ImportError(module)
return sys.modules[module]
# Not really compat but convenient
try:
from log_colorizer import get_color_logger
except ImportError:
import logging
logger = logging.getLogger
else:
logger = get_color_logger