1 from __future__ import unicode_literals
14 import urllib.request as compat_urllib_request
15 except ImportError: # Python 2
16 import urllib2 as compat_urllib_request
19 import urllib.error as compat_urllib_error
20 except ImportError: # Python 2
21 import urllib2 as compat_urllib_error
24 import urllib.parse as compat_urllib_parse
25 except ImportError: # Python 2
26 import urllib as compat_urllib_parse
29 from urllib.parse import urlparse as compat_urllib_parse_urlparse
30 except ImportError: # Python 2
31 from urlparse import urlparse as compat_urllib_parse_urlparse
34 import urllib.parse as compat_urlparse
35 except ImportError: # Python 2
36 import urlparse as compat_urlparse
39 import http.cookiejar as compat_cookiejar
40 except ImportError: # Python 2
41 import cookielib as compat_cookiejar
44 import html.entities as compat_html_entities
45 except ImportError: # Python 2
46 import htmlentitydefs as compat_html_entities
49 import html.parser as compat_html_parser
50 except ImportError: # Python 2
51 import HTMLParser as compat_html_parser
54 import http.client as compat_http_client
55 except ImportError: # Python 2
56 import httplib as compat_http_client
59 from urllib.error import HTTPError as compat_HTTPError
60 except ImportError: # Python 2
61 from urllib2 import HTTPError as compat_HTTPError
64 from urllib.request import urlretrieve as compat_urlretrieve
65 except ImportError: # Python 2
66 from urllib import urlretrieve as compat_urlretrieve
70 from subprocess import DEVNULL
71 compat_subprocess_get_DEVNULL = lambda: DEVNULL
73 compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
76 from urllib.parse import unquote as compat_urllib_parse_unquote
78 def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
81 res = string.split('%')
88 # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
95 pct_sequence += item[:2].decode('hex')
98 # This segment was just a single percent-encoded character.
99 # May be part of a sequence of code units, so delay decoding.
100 # (Stored in pct_sequence).
104 # Encountered non-percent-encoded characters. Flush the current
106 string += pct_sequence.decode(encoding, errors) + rest
109 # Flush the final pct_sequence
110 string += pct_sequence.decode(encoding, errors)
115 from urllib.parse import parse_qs as compat_parse_qs
116 except ImportError: # Python 2
117 # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
118 # Python 2's version is apparently totally broken
120 def _parse_qsl(qs, keep_blank_values=False, strict_parsing=False,
121 encoding='utf-8', errors='replace'):
122 qs, _coerce_result = qs, unicode
123 pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
125 for name_value in pairs:
126 if not name_value and not strict_parsing:
128 nv = name_value.split('=', 1)
131 raise ValueError("bad query field: %r" % (name_value,))
132 # Handle case of a control-name with no equal sign
133 if keep_blank_values:
137 if len(nv[1]) or keep_blank_values:
138 name = nv[0].replace('+', ' ')
139 name = compat_urllib_parse_unquote(
140 name, encoding=encoding, errors=errors)
141 name = _coerce_result(name)
142 value = nv[1].replace('+', ' ')
143 value = compat_urllib_parse_unquote(
144 value, encoding=encoding, errors=errors)
145 value = _coerce_result(value)
146 r.append((name, value))
149 def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
150 encoding='utf-8', errors='replace'):
152 pairs = _parse_qsl(qs, keep_blank_values, strict_parsing,
153 encoding=encoding, errors=errors)
154 for name, value in pairs:
155 if name in parsed_result:
156 parsed_result[name].append(value)
158 parsed_result[name] = [value]
162 compat_str = unicode # Python 2
167 compat_chr = unichr # Python 2
172 from xml.etree.ElementTree import ParseError as compat_xml_parse_error
173 except ImportError: # Python 2.6
174 from xml.parsers.expat import ExpatError as compat_xml_parse_error
177 from shlex import quote as shlex_quote
178 except ImportError: # Python < 3.3
180 if re.match(r'^[-_\w./]+$', s):
183 return "'" + s.replace("'", "'\"'\"'") + "'"
193 if sys.version_info >= (3, 0):
194 compat_getenv = os.getenv
195 compat_expanduser = os.path.expanduser
197 # Environment variables should be decoded with filesystem encoding.
198 # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
200 def compat_getenv(key, default=None):
201 from .utils import get_filesystem_encoding
202 env = os.getenv(key, default)
204 env = env.decode(get_filesystem_encoding())
207 # HACK: The default implementations of os.path.expanduser from cpython do not decode
208 # environment variables with filesystem encoding. We will work around this by
209 # providing adjusted implementations.
210 # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
211 # for different platforms with correct environment variables decoding.
213 if os.name == 'posix':
214 def compat_expanduser(path):
215 """Expand ~ and ~user constructions. If user or $HOME is unknown,
217 if not path.startswith('~'):
219 i = path.find('/', 1)
223 if 'HOME' not in os.environ:
225 userhome = pwd.getpwuid(os.getuid()).pw_dir
227 userhome = compat_getenv('HOME')
231 pwent = pwd.getpwnam(path[1:i])
234 userhome = pwent.pw_dir
235 userhome = userhome.rstrip('/')
236 return (userhome + path[i:]) or '/'
237 elif os.name == 'nt' or os.name == 'ce':
238 def compat_expanduser(path):
239 """Expand ~ and ~user constructs.
241 If user or $HOME is unknown, do nothing."""
245 while i < n and path[i] not in '/\\':
248 if 'HOME' in os.environ:
249 userhome = compat_getenv('HOME')
250 elif 'USERPROFILE' in os.environ:
251 userhome = compat_getenv('USERPROFILE')
252 elif 'HOMEPATH' not in os.environ:
256 drive = compat_getenv('HOMEDRIVE')
259 userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
262 userhome = os.path.join(os.path.dirname(userhome), path[1:i])
264 return userhome + path[i:]
266 compat_expanduser = os.path.expanduser
269 if sys.version_info < (3, 0):
271 from .utils import preferredencoding
272 print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
275 assert isinstance(s, compat_str)
280 subprocess_check_output = subprocess.check_output
281 except AttributeError:
282 def subprocess_check_output(*args, **kwargs):
283 assert 'input' not in kwargs
284 p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
285 output, _ = p.communicate()
288 raise subprocess.CalledProcessError(ret, p.args, output=output)
291 if sys.version_info < (3, 0) and sys.platform == 'win32':
292 def compat_getpass(prompt, *args, **kwargs):
293 if isinstance(prompt, compat_str):
294 from .utils import preferredencoding
295 prompt = prompt.encode(preferredencoding())
296 return getpass.getpass(prompt, *args, **kwargs)
298 compat_getpass = getpass.getpass
300 # Old 2.6 and 2.7 releases require kwargs to be bytes
302 (lambda x: x)(**{'x': 0})
304 def compat_kwargs(kwargs):
305 return dict((bytes(k), v) for k, v in kwargs.items())
307 compat_kwargs = lambda kwargs: kwargs
310 # Fix https://github.com/rg3/youtube-dl/issues/4223
311 # See http://bugs.python.org/issue9161 for what is broken
312 def workaround_optparse_bug9161():
313 op = optparse.OptionParser()
314 og = optparse.OptionGroup(op, 'foo')
318 real_add_option = optparse.OptionGroup.add_option
320 def _compat_add_option(self, *args, **kwargs):
322 v.encode('ascii', 'replace') if isinstance(v, compat_str)
324 bargs = [enc(a) for a in args]
326 (k, enc(v)) for k, v in kwargs.items())
327 return real_add_option(self, *bargs, **bkwargs)
328 optparse.OptionGroup.add_option = _compat_add_option
331 if platform.python_implementation() == 'PyPy':
332 # PyPy expects byte strings as Windows function names
333 # https://github.com/rg3/youtube-dl/pull/4392
334 def compat_WINFUNCTYPE(*args, **kwargs):
335 real = ctypes.WINFUNCTYPE(*args, **kwargs)
337 def resf(tpl, *args, **kwargs):
339 return real((str(funcname), dll), *args, **kwargs)
343 def compat_WINFUNCTYPE(*args, **kwargs):
344 return ctypes.WINFUNCTYPE(*args, **kwargs)
354 'compat_html_entities',
355 'compat_html_parser',
356 'compat_http_client',
362 'compat_subprocess_get_DEVNULL',
363 'compat_urllib_error',
364 'compat_urllib_parse',
365 'compat_urllib_parse_unquote',
366 'compat_urllib_parse_urlparse',
367 'compat_urllib_request',
369 'compat_urlretrieve',
370 'compat_WINFUNCTYPE',
371 'compat_xml_parse_error',
373 'subprocess_check_output',
374 'workaround_optparse_bug9161',