1 from __future__
import unicode_literals
13 import urllib
.request
as compat_urllib_request
14 except ImportError: # Python 2
15 import urllib2
as compat_urllib_request
18 import urllib
.error
as compat_urllib_error
19 except ImportError: # Python 2
20 import urllib2
as compat_urllib_error
23 import urllib
.parse
as compat_urllib_parse
24 except ImportError: # Python 2
25 import urllib
as compat_urllib_parse
28 from urllib
.parse
import urlparse
as compat_urllib_parse_urlparse
29 except ImportError: # Python 2
30 from urlparse
import urlparse
as compat_urllib_parse_urlparse
33 import urllib
.parse
as compat_urlparse
34 except ImportError: # Python 2
35 import urlparse
as compat_urlparse
38 import http
.cookiejar
as compat_cookiejar
39 except ImportError: # Python 2
40 import cookielib
as compat_cookiejar
43 import html
.entities
as compat_html_entities
44 except ImportError: # Python 2
45 import htmlentitydefs
as compat_html_entities
48 import html
.parser
as compat_html_parser
49 except ImportError: # Python 2
50 import HTMLParser
as compat_html_parser
53 import http
.client
as compat_http_client
54 except ImportError: # Python 2
55 import httplib
as compat_http_client
58 from urllib
.error
import HTTPError
as compat_HTTPError
59 except ImportError: # Python 2
60 from urllib2
import HTTPError
as compat_HTTPError
63 from urllib
.request
import urlretrieve
as compat_urlretrieve
64 except ImportError: # Python 2
65 from urllib
import urlretrieve
as compat_urlretrieve
69 from subprocess
import DEVNULL
70 compat_subprocess_get_DEVNULL
= lambda: DEVNULL
72 compat_subprocess_get_DEVNULL
= lambda: open(os
.path
.devnull
, 'w')
75 from urllib
.parse
import unquote
as compat_urllib_parse_unquote
77 def compat_urllib_parse_unquote(string
, encoding
='utf-8', errors
='replace'):
80 res
= string
.split('%')
87 # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
94 pct_sequence
+= item
[:2].decode('hex')
97 # This segment was just a single percent-encoded character.
98 # May be part of a sequence of code units, so delay decoding.
99 # (Stored in pct_sequence).
103 # Encountered non-percent-encoded characters. Flush the current
105 string
+= pct_sequence
.decode(encoding
, errors
) + rest
108 # Flush the final pct_sequence
109 string
+= pct_sequence
.decode(encoding
, errors
)
114 from urllib
.parse
import parse_qs
as compat_parse_qs
115 except ImportError: # Python 2
116 # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
117 # Python 2's version is apparently totally broken
119 def _parse_qsl(qs
, keep_blank_values
=False, strict_parsing
=False,
120 encoding
='utf-8', errors
='replace'):
121 qs
, _coerce_result
= qs
, unicode
122 pairs
= [s2
for s1
in qs
.split('&') for s2
in s1
.split(';')]
124 for name_value
in pairs
:
125 if not name_value
and not strict_parsing
:
127 nv
= name_value
.split('=', 1)
130 raise ValueError("bad query field: %r" % (name_value
,))
131 # Handle case of a control-name with no equal sign
132 if keep_blank_values
:
136 if len(nv
[1]) or keep_blank_values
:
137 name
= nv
[0].replace('+', ' ')
138 name
= compat_urllib_parse_unquote(
139 name
, encoding
=encoding
, errors
=errors
)
140 name
= _coerce_result(name
)
141 value
= nv
[1].replace('+', ' ')
142 value
= compat_urllib_parse_unquote(
143 value
, encoding
=encoding
, errors
=errors
)
144 value
= _coerce_result(value
)
145 r
.append((name
, value
))
148 def compat_parse_qs(qs
, keep_blank_values
=False, strict_parsing
=False,
149 encoding
='utf-8', errors
='replace'):
151 pairs
= _parse_qsl(qs
, keep_blank_values
, strict_parsing
,
152 encoding
=encoding
, errors
=errors
)
153 for name
, value
in pairs
:
154 if name
in parsed_result
:
155 parsed_result
[name
].append(value
)
157 parsed_result
[name
] = [value
]
161 compat_str
= unicode # Python 2
166 compat_chr
= unichr # Python 2
171 from xml
.etree
.ElementTree
import ParseError
as compat_xml_parse_error
172 except ImportError: # Python 2.6
173 from xml
.parsers
.expat
import ExpatError
as compat_xml_parse_error
176 from shlex
import quote
as shlex_quote
177 except ImportError: # Python < 3.3
179 if re
.match(r
'^[-_\w./]+$', s
):
182 return "'" + s
.replace("'", "'\"'\"'") + "'"
192 if sys
.version_info
>= (3, 0):
193 compat_getenv
= os
.getenv
194 compat_expanduser
= os
.path
.expanduser
196 # Environment variables should be decoded with filesystem encoding.
197 # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
199 def compat_getenv(key
, default
=None):
200 from .utils
import get_filesystem_encoding
201 env
= os
.getenv(key
, default
)
203 env
= env
.decode(get_filesystem_encoding())
206 # HACK: The default implementations of os.path.expanduser from cpython do not decode
207 # environment variables with filesystem encoding. We will work around this by
208 # providing adjusted implementations.
209 # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
210 # for different platforms with correct environment variables decoding.
212 if os
.name
== 'posix':
213 def compat_expanduser(path
):
214 """Expand ~ and ~user constructions. If user or $HOME is unknown,
216 if not path
.startswith('~'):
218 i
= path
.find('/', 1)
222 if 'HOME' not in os
.environ
:
224 userhome
= pwd
.getpwuid(os
.getuid()).pw_dir
226 userhome
= compat_getenv('HOME')
230 pwent
= pwd
.getpwnam(path
[1:i
])
233 userhome
= pwent
.pw_dir
234 userhome
= userhome
.rstrip('/')
235 return (userhome
+ path
[i
:]) or '/'
236 elif os
.name
== 'nt' or os
.name
== 'ce':
237 def compat_expanduser(path
):
238 """Expand ~ and ~user constructs.
240 If user or $HOME is unknown, do nothing."""
244 while i
< n
and path
[i
] not in '/\\':
247 if 'HOME' in os
.environ
:
248 userhome
= compat_getenv('HOME')
249 elif 'USERPROFILE' in os
.environ
:
250 userhome
= compat_getenv('USERPROFILE')
251 elif 'HOMEPATH' not in os
.environ
:
255 drive
= compat_getenv('HOMEDRIVE')
258 userhome
= os
.path
.join(drive
, compat_getenv('HOMEPATH'))
261 userhome
= os
.path
.join(os
.path
.dirname(userhome
), path
[1:i
])
263 return userhome
+ path
[i
:]
265 compat_expanduser
= os
.path
.expanduser
268 if sys
.version_info
< (3, 0):
270 from .utils
import preferredencoding
271 print(s
.encode(preferredencoding(), 'xmlcharrefreplace'))
274 assert isinstance(s
, compat_str
)
279 subprocess_check_output
= subprocess
.check_output
280 except AttributeError:
281 def subprocess_check_output(*args
, **kwargs
):
282 assert 'input' not in kwargs
283 p
= subprocess
.Popen(*args
, stdout
=subprocess
.PIPE
, **kwargs
)
284 output
, _
= p
.communicate()
287 raise subprocess
.CalledProcessError(ret
, p
.args
, output
=output
)
290 if sys
.version_info
< (3, 0) and sys
.platform
== 'win32':
291 def compat_getpass(prompt
, *args
, **kwargs
):
292 if isinstance(prompt
, compat_str
):
293 from .utils
import preferredencoding
294 prompt
= prompt
.encode(preferredencoding())
295 return getpass
.getpass(prompt
, *args
, **kwargs
)
297 compat_getpass
= getpass
.getpass
299 # Old 2.6 and 2.7 releases require kwargs to be bytes
303 _testfunc(**{'x': 0})
305 def compat_kwargs(kwargs
):
306 return dict((bytes(k
), v
) for k
, v
in kwargs
.items())
308 compat_kwargs
= lambda kwargs
: kwargs
311 if sys
.version_info
< (2, 7):
312 def compat_socket_create_connection(address
, timeout
, source_address
=None):
315 for res
in socket
.getaddrinfo(host
, port
, 0, socket
.SOCK_STREAM
):
316 af
, socktype
, proto
, canonname
, sa
= res
319 sock
= socket
.socket(af
, socktype
, proto
)
320 sock
.settimeout(timeout
)
322 sock
.bind(source_address
)
325 except socket
.error
as _
:
332 raise socket
.error("getaddrinfo returns an empty list")
334 compat_socket_create_connection
= socket
.create_connection
337 # Fix https://github.com/rg3/youtube-dl/issues/4223
338 # See http://bugs.python.org/issue9161 for what is broken
339 def workaround_optparse_bug9161():
340 op
= optparse
.OptionParser()
341 og
= optparse
.OptionGroup(op
, 'foo')
345 real_add_option
= optparse
.OptionGroup
.add_option
347 def _compat_add_option(self
, *args
, **kwargs
):
349 v
.encode('ascii', 'replace') if isinstance(v
, compat_str
)
351 bargs
= [enc(a
) for a
in args
]
353 (k
, enc(v
)) for k
, v
in kwargs
.items())
354 return real_add_option(self
, *bargs
, **bkwargs
)
355 optparse
.OptionGroup
.add_option
= _compat_add_option
365 'compat_html_entities',
366 'compat_html_parser',
367 'compat_http_client',
372 'compat_socket_create_connection',
374 'compat_subprocess_get_DEVNULL',
375 'compat_urllib_error',
376 'compat_urllib_parse',
377 'compat_urllib_parse_unquote',
378 'compat_urllib_parse_urlparse',
379 'compat_urllib_request',
381 'compat_urlretrieve',
382 'compat_xml_parse_error',
384 'subprocess_check_output',
385 'workaround_optparse_bug9161',