1 from __future__ import unicode_literals
16 import urllib.request as compat_urllib_request
17 except ImportError: # Python 2
18 import urllib2 as compat_urllib_request
21 import urllib.error as compat_urllib_error
22 except ImportError: # Python 2
23 import urllib2 as compat_urllib_error
26 import urllib.parse as compat_urllib_parse
27 except ImportError: # Python 2
28 import urllib as compat_urllib_parse
31 from urllib.parse import urlparse as compat_urllib_parse_urlparse
32 except ImportError: # Python 2
33 from urlparse import urlparse as compat_urllib_parse_urlparse
36 import urllib.parse as compat_urlparse
37 except ImportError: # Python 2
38 import urlparse as compat_urlparse
41 import http.cookiejar as compat_cookiejar
42 except ImportError: # Python 2
43 import cookielib as compat_cookiejar
46 import html.entities as compat_html_entities
47 except ImportError: # Python 2
48 import htmlentitydefs as compat_html_entities
51 import http.client as compat_http_client
52 except ImportError: # Python 2
53 import httplib as compat_http_client
56 from urllib.error import HTTPError as compat_HTTPError
57 except ImportError: # Python 2
58 from urllib2 import HTTPError as compat_HTTPError
61 from urllib.request import urlretrieve as compat_urlretrieve
62 except ImportError: # Python 2
63 from urllib import urlretrieve as compat_urlretrieve
67 from subprocess import DEVNULL
68 compat_subprocess_get_DEVNULL = lambda: DEVNULL
70 compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
73 import http.server as compat_http_server
75 import BaseHTTPServer as compat_http_server
77 from pprint import (pprint, pformat)
81 sys.stderr.write(pformat(fmt) + "\n")
84 from urllib.parse import unquote as compat_urllib_parse_unquote
86 def compat_urllib_parse_unquote_to_bytes(string):
87 """unquote_to_bytes('abc%20def') -> b'abc def'."""
88 # Note: strings are encoded as UTF-8. This is only an issue if it contains
89 # unescaped non-ASCII characters, which URIs should not.
91 # Is it a string-like object?
94 if isinstance(string, str):
95 string = string.encode('utf-8')
96 # string = encode('utf-8')
98 # python3 -> 2: must implicitly convert to bits
99 bits = bytes(string).split(b'%')
106 for item in bits[1:]:
108 append(item[:2].decode('hex'))
115 compat_urllib_parse_asciire = re.compile('([\x00-\x7f]+)')
117 def new_compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
118 """Replace %xx escapes by their single-character equivalent. The optional
119 encoding and errors parameters specify how to decode percent-encoded
120 sequences into Unicode characters, as accepted by the bytes.decode()
122 By default, percent-encoded sequences are decoded with UTF-8, and invalid
123 sequences are replaced by a placeholder character.
125 unquote('abc%20def') -> 'abc def'.
128 if '%' not in string:
136 bits = compat_urllib_parse_asciire.split(string)
139 for i in range(1, len(bits), 2):
140 foo = compat_urllib_parse_unquote_to_bytes(bits[i])
141 foo = foo.decode(encoding, errors)
146 if not isinstance(bar, unicode):
147 bar = bar.decode('utf-8')
151 def old_compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
154 res = string.split('%')
161 # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
168 if not re.match('[0-9a-fA-F][0-9a-fA-F]',item[:2]):
170 pct_sequence += item[:2].decode('hex')
173 # This segment was just a single percent-encoded character.
174 # May be part of a sequence of code units, so delay decoding.
175 # (Stored in pct_sequence).
179 # Encountered non-percent-encoded characters. Flush the current
181 string += pct_sequence.decode(encoding, errors) + rest
184 # Flush the final pct_sequence
185 string += pct_sequence.decode(encoding, errors)
188 compat_urllib_parse_unquote = new_compat_urllib_parse_unquote
191 compat_str = unicode # Python 2
196 compat_basestring = basestring # Python 2
198 compat_basestring = str
201 compat_chr = unichr # Python 2
206 from xml.etree.ElementTree import ParseError as compat_xml_parse_error
207 except ImportError: # Python 2.6
208 from xml.parsers.expat import ExpatError as compat_xml_parse_error
212 from urllib.parse import parse_qs as compat_parse_qs
213 except ImportError: # Python 2
214 # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
215 # Python 2's version is apparently totally broken
217 def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
218 encoding='utf-8', errors='replace'):
219 qs, _coerce_result = qs, compat_str
220 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
222 for name_value in pairs:
223 if not name_value and not strict_parsing:
225 nv = name_value.split('=', 1)
228 raise ValueError("bad query field: %r" % (name_value,))
229 # Handle case of a control-name with no equal sign
230 if keep_blank_values:
234 if len(nv[1]) or keep_blank_values:
235 name = nv[0].replace('+', ' ')
236 name = compat_urllib_parse_unquote(
237 name, encoding=encoding, errors=errors)
238 name = _coerce_result(name)
239 value = nv[1].replace('+', ' ')
240 value = compat_urllib_parse_unquote(
241 value, encoding=encoding, errors=errors)
242 value = _coerce_result(value)
243 r.append((name, value))
246 def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
247 encoding='utf-8', errors='replace'):
249 pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
250 encoding=encoding, errors=errors)
251 for name, value in pairs:
252 if name in parsed_result:
253 parsed_result[name].append(value)
255 parsed_result[name] = [value]
259 from shlex import quote as shlex_quote
260 except ImportError: # Python < 3.3
262 if re.match(r'^[-_\w./]+$', s):
265 return "'" + s.replace("'", "'\"'\"'") + "'"
275 if sys.version_info >= (3, 0):
276 compat_getenv = os.getenv
277 compat_expanduser = os.path.expanduser
279 # Environment variables should be decoded with filesystem encoding.
280 # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
282 def compat_getenv(key, default=None):
283 from .utils import get_filesystem_encoding
284 env = os.getenv(key, default)
286 env = env.decode(get_filesystem_encoding())
289 # HACK: The default implementations of os.path.expanduser from cpython do not decode
290 # environment variables with filesystem encoding. We will work around this by
291 # providing adjusted implementations.
292 # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
293 # for different platforms with correct environment variables decoding.
295 if os.name == 'posix':
296 def compat_expanduser(path):
297 """Expand ~ and ~user constructions. If user or $HOME is unknown,
299 if not path.startswith('~'):
301 i = path.find('/', 1)
305 if 'HOME' not in os.environ:
307 userhome = pwd.getpwuid(os.getuid()).pw_dir
309 userhome = compat_getenv('HOME')
313 pwent = pwd.getpwnam(path[1:i])
316 userhome = pwent.pw_dir
317 userhome = userhome.rstrip('/')
318 return (userhome + path[i:]) or '/'
319 elif os.name == 'nt' or os.name == 'ce':
320 def compat_expanduser(path):
321 """Expand ~ and ~user constructs.
323 If user or $HOME is unknown, do nothing."""
327 while i < n and path[i] not in '/\\':
330 if 'HOME' in os.environ:
331 userhome = compat_getenv('HOME')
332 elif 'USERPROFILE' in os.environ:
333 userhome = compat_getenv('USERPROFILE')
334 elif 'HOMEPATH' not in os.environ:
338 drive = compat_getenv('HOMEDRIVE')
341 userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
344 userhome = os.path.join(os.path.dirname(userhome), path[1:i])
346 return userhome + path[i:]
348 compat_expanduser = os.path.expanduser
351 if sys.version_info < (3, 0):
353 from .utils import preferredencoding
354 print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
357 assert isinstance(s, compat_str)
362 subprocess_check_output = subprocess.check_output
363 except AttributeError:
364 def subprocess_check_output(*args, **kwargs):
365 assert 'input' not in kwargs
366 p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
367 output, _ = p.communicate()
370 raise subprocess.CalledProcessError(ret, p.args, output=output)
373 if sys.version_info < (3, 0) and sys.platform == 'win32':
374 def compat_getpass(prompt, *args, **kwargs):
375 if isinstance(prompt, compat_str):
376 from .utils import preferredencoding
377 prompt = prompt.encode(preferredencoding())
378 return getpass.getpass(prompt, *args, **kwargs)
380 compat_getpass = getpass.getpass
382 # Old 2.6 and 2.7 releases require kwargs to be bytes
386 _testfunc(**{'x': 0})
388 def compat_kwargs(kwargs):
389 return dict((bytes(k), v) for k, v in kwargs.items())
391 compat_kwargs = lambda kwargs: kwargs
394 if sys.version_info < (2, 7):
395 def compat_socket_create_connection(address, timeout, source_address=None):
398 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
399 af, socktype, proto, canonname, sa = res
402 sock = socket.socket(af, socktype, proto)
403 sock.settimeout(timeout)
405 sock.bind(source_address)
408 except socket.error as _:
415 raise socket.error("getaddrinfo returns an empty list")
417 compat_socket_create_connection = socket.create_connection
420 # Fix https://github.com/rg3/youtube-dl/issues/4223
421 # See http://bugs.python.org/issue9161 for what is broken
422 def workaround_optparse_bug9161():
423 op = optparse.OptionParser()
424 og = optparse.OptionGroup(op, 'foo')
428 real_add_option = optparse.OptionGroup.add_option
430 def _compat_add_option(self, *args, **kwargs):
432 v.encode('ascii', 'replace') if isinstance(v, compat_str)
434 bargs = [enc(a) for a in args]
436 (k, enc(v)) for k, v in kwargs.items())
437 return real_add_option(self, *bargs, **bkwargs)
438 optparse.OptionGroup.add_option = _compat_add_option
440 if hasattr(shutil, 'get_terminal_size'): # Python >= 3.3
441 compat_get_terminal_size = shutil.get_terminal_size
443 _terminal_size = collections.namedtuple('terminal_size', ['columns', 'lines'])
445 def compat_get_terminal_size():
446 columns = compat_getenv('COLUMNS', None)
448 columns = int(columns)
451 lines = compat_getenv('LINES', None)
458 sp = subprocess.Popen(
460 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
461 out, err = sp.communicate()
462 lines, columns = map(int, out.split())
465 return _terminal_size(columns, lines)
468 itertools.count(start=0, step=1)
469 compat_itertools_count = itertools.count
470 except TypeError: # Python 2.6
471 def compat_itertools_count(start=0, step=1):
483 'compat_get_terminal_size',
486 'compat_html_entities',
487 'compat_http_client',
488 'compat_http_server',
489 'compat_itertools_count',
494 'compat_socket_create_connection',
496 'compat_subprocess_get_DEVNULL',
497 'compat_urllib_error',
498 'compat_urllib_parse',
499 'compat_urllib_parse_unquote',
500 'compat_urllib_parse_urlparse',
501 'compat_urllib_request',
503 'compat_urlretrieve',
504 'compat_xml_parse_error',
506 'subprocess_check_output',
507 'workaround_optparse_bug9161',