1 from __future__
import unicode_literals
12 import urllib
.request
as compat_urllib_request
13 except ImportError: # Python 2
14 import urllib2
as compat_urllib_request
17 import urllib
.error
as compat_urllib_error
18 except ImportError: # Python 2
19 import urllib2
as compat_urllib_error
22 import urllib
.parse
as compat_urllib_parse
23 except ImportError: # Python 2
24 import urllib
as compat_urllib_parse
27 from urllib
.parse
import urlparse
as compat_urllib_parse_urlparse
28 except ImportError: # Python 2
29 from urlparse
import urlparse
as compat_urllib_parse_urlparse
32 import urllib
.parse
as compat_urlparse
33 except ImportError: # Python 2
34 import urlparse
as compat_urlparse
37 import http
.cookiejar
as compat_cookiejar
38 except ImportError: # Python 2
39 import cookielib
as compat_cookiejar
42 import html
.entities
as compat_html_entities
43 except ImportError: # Python 2
44 import htmlentitydefs
as compat_html_entities
47 import html
.parser
as compat_html_parser
48 except ImportError: # Python 2
49 import HTMLParser
as compat_html_parser
52 import http
.client
as compat_http_client
53 except ImportError: # Python 2
54 import httplib
as compat_http_client
57 from urllib
.error
import HTTPError
as compat_HTTPError
58 except ImportError: # Python 2
59 from urllib2
import HTTPError
as compat_HTTPError
62 from urllib
.request
import urlretrieve
as compat_urlretrieve
63 except ImportError: # Python 2
64 from urllib
import urlretrieve
as compat_urlretrieve
68 from subprocess
import DEVNULL
69 compat_subprocess_get_DEVNULL
= lambda: DEVNULL
71 compat_subprocess_get_DEVNULL
= lambda: open(os
.path
.devnull
, 'w')
74 from urllib
.parse
import unquote
as compat_urllib_parse_unquote
76 def compat_urllib_parse_unquote(string
, encoding
='utf-8', errors
='replace'):
79 res
= string
.split('%')
86 # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
93 pct_sequence
+= item
[:2].decode('hex')
96 # This segment was just a single percent-encoded character.
97 # May be part of a sequence of code units, so delay decoding.
98 # (Stored in pct_sequence).
102 # Encountered non-percent-encoded characters. Flush the current
104 string
+= pct_sequence
.decode(encoding
, errors
) + rest
107 # Flush the final pct_sequence
108 string
+= pct_sequence
.decode(encoding
, errors
)
113 from urllib
.parse
import parse_qs
as compat_parse_qs
114 except ImportError: # Python 2
115 # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
116 # Python 2's version is apparently totally broken
118 def _parse_qsl(qs
, keep_blank_values
=False, strict_parsing
=False,
119 encoding
='utf-8', errors
='replace'):
120 qs
, _coerce_result
= qs
, unicode
121 pairs
= [s2
for s1
in qs
.split('&') for s2
in s1
.split(';')]
123 for name_value
in pairs
:
124 if not name_value
and not strict_parsing
:
126 nv
= name_value
.split('=', 1)
129 raise ValueError("bad query field: %r" % (name_value
,))
130 # Handle case of a control-name with no equal sign
131 if keep_blank_values
:
135 if len(nv
[1]) or keep_blank_values
:
136 name
= nv
[0].replace('+', ' ')
137 name
= compat_urllib_parse_unquote(
138 name
, encoding
=encoding
, errors
=errors
)
139 name
= _coerce_result(name
)
140 value
= nv
[1].replace('+', ' ')
141 value
= compat_urllib_parse_unquote(
142 value
, encoding
=encoding
, errors
=errors
)
143 value
= _coerce_result(value
)
144 r
.append((name
, value
))
147 def compat_parse_qs(qs
, keep_blank_values
=False, strict_parsing
=False,
148 encoding
='utf-8', errors
='replace'):
150 pairs
= _parse_qsl(qs
, keep_blank_values
, strict_parsing
,
151 encoding
=encoding
, errors
=errors
)
152 for name
, value
in pairs
:
153 if name
in parsed_result
:
154 parsed_result
[name
].append(value
)
156 parsed_result
[name
] = [value
]
160 compat_str
= unicode # Python 2
165 compat_chr
= unichr # Python 2
170 from xml
.etree
.ElementTree
import ParseError
as compat_xml_parse_error
171 except ImportError: # Python 2.6
172 from xml
.parsers
.expat
import ExpatError
as compat_xml_parse_error
175 from shlex
import quote
as shlex_quote
176 except ImportError: # Python < 3.3
178 if re
.match(r
'^[-_\w./]+$', s
):
181 return "'" + s
.replace("'", "'\"'\"'") + "'"
191 if sys
.version_info
>= (3, 0):
192 compat_getenv
= os
.getenv
193 compat_expanduser
= os
.path
.expanduser
195 # Environment variables should be decoded with filesystem encoding.
196 # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
198 def compat_getenv(key
, default
=None):
199 from .utils
import get_filesystem_encoding
200 env
= os
.getenv(key
, default
)
202 env
= env
.decode(get_filesystem_encoding())
205 # HACK: The default implementations of os.path.expanduser from cpython do not decode
206 # environment variables with filesystem encoding. We will work around this by
207 # providing adjusted implementations.
208 # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
209 # for different platforms with correct environment variables decoding.
211 if os
.name
== 'posix':
212 def compat_expanduser(path
):
213 """Expand ~ and ~user constructions. If user or $HOME is unknown,
215 if not path
.startswith('~'):
217 i
= path
.find('/', 1)
221 if 'HOME' not in os
.environ
:
223 userhome
= pwd
.getpwuid(os
.getuid()).pw_dir
225 userhome
= compat_getenv('HOME')
229 pwent
= pwd
.getpwnam(path
[1:i
])
232 userhome
= pwent
.pw_dir
233 userhome
= userhome
.rstrip('/')
234 return (userhome
+ path
[i
:]) or '/'
235 elif os
.name
== 'nt' or os
.name
== 'ce':
236 def compat_expanduser(path
):
237 """Expand ~ and ~user constructs.
239 If user or $HOME is unknown, do nothing."""
243 while i
< n
and path
[i
] not in '/\\':
246 if 'HOME' in os
.environ
:
247 userhome
= compat_getenv('HOME')
248 elif 'USERPROFILE' in os
.environ
:
249 userhome
= compat_getenv('USERPROFILE')
250 elif not 'HOMEPATH' in os
.environ
:
254 drive
= compat_getenv('HOMEDRIVE')
257 userhome
= os
.path
.join(drive
, compat_getenv('HOMEPATH'))
260 userhome
= os
.path
.join(os
.path
.dirname(userhome
), path
[1:i
])
262 return userhome
+ path
[i
:]
264 compat_expanduser
= os
.path
.expanduser
267 if sys
.version_info
< (3, 0):
269 from .utils
import preferredencoding
270 print(s
.encode(preferredencoding(), 'xmlcharrefreplace'))
273 assert isinstance(s
, compat_str
)
278 subprocess_check_output
= subprocess
.check_output
279 except AttributeError:
280 def subprocess_check_output(*args
, **kwargs
):
281 assert 'input' not in kwargs
282 p
= subprocess
.Popen(*args
, stdout
=subprocess
.PIPE
, **kwargs
)
283 output
, _
= p
.communicate()
286 raise subprocess
.CalledProcessError(ret
, p
.args
, output
=output
)
289 if sys
.version_info
< (3, 0) and sys
.platform
== 'win32':
290 def compat_getpass(prompt
, *args
, **kwargs
):
291 if isinstance(prompt
, compat_str
):
292 from .utils
import preferredencoding
293 prompt
= prompt
.encode(preferredencoding())
294 return getpass
.getpass(prompt
, *args
, **kwargs
)
296 compat_getpass
= getpass
.getpass
298 # Old 2.6 and 2.7 releases require kwargs to be bytes
300 (lambda x
: x
)(**{'x': 0})
302 def compat_kwargs(kwargs
):
303 return dict((bytes(k
), v
) for k
, v
in kwargs
.items())
305 compat_kwargs
= lambda kwargs
: kwargs
308 # Fix https://github.com/rg3/youtube-dl/issues/4223
309 # See http://bugs.python.org/issue9161 for what is broken
310 def workaround_optparse_bug9161():
311 op
= optparse
.OptionParser()
312 og
= optparse
.OptionGroup(op
, 'foo')
316 real_add_option
= optparse
.OptionGroup
.add_option
318 def _compat_add_option(self
, *args
, **kwargs
):
320 v
.encode('ascii', 'replace') if isinstance(v
, compat_str
)
322 bargs
= [enc(a
) for a
in args
]
324 (k
, enc(v
)) for k
, v
in kwargs
.items())
325 return real_add_option(self
, *bargs
, **bkwargs
)
326 optparse
.OptionGroup
.add_option
= _compat_add_option
336 'compat_html_entities',
337 'compat_html_parser',
338 'compat_http_client',
344 'compat_subprocess_get_DEVNULL',
345 'compat_urllib_error',
346 'compat_urllib_parse',
347 'compat_urllib_parse_unquote',
348 'compat_urllib_parse_urlparse',
349 'compat_urllib_request',
351 'compat_urlretrieve',
352 'compat_xml_parse_error',
354 'subprocess_check_output',
355 'workaround_optparse_bug9161',