compat.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. from __future__ import unicode_literals
  2. import getpass
  3. import optparse
  4. import os
  5. import re
  6. import socket
  7. import subprocess
  8. import sys
  9. try:
  10. import urllib.request as compat_urllib_request
  11. except ImportError: # Python 2
  12. import urllib2 as compat_urllib_request
  13. try:
  14. import urllib.error as compat_urllib_error
  15. except ImportError: # Python 2
  16. import urllib2 as compat_urllib_error
  17. try:
  18. import urllib.parse as compat_urllib_parse
  19. except ImportError: # Python 2
  20. import urllib as compat_urllib_parse
  21. try:
  22. from urllib.parse import urlparse as compat_urllib_parse_urlparse
  23. except ImportError: # Python 2
  24. from urlparse import urlparse as compat_urllib_parse_urlparse
  25. try:
  26. import urllib.parse as compat_urlparse
  27. except ImportError: # Python 2
  28. import urlparse as compat_urlparse
  29. try:
  30. import http.cookiejar as compat_cookiejar
  31. except ImportError: # Python 2
  32. import cookielib as compat_cookiejar
  33. try:
  34. import html.entities as compat_html_entities
  35. except ImportError: # Python 2
  36. import htmlentitydefs as compat_html_entities
  37. try:
  38. import html.parser as compat_html_parser
  39. except ImportError: # Python 2
  40. import HTMLParser as compat_html_parser
  41. try:
  42. import http.client as compat_http_client
  43. except ImportError: # Python 2
  44. import httplib as compat_http_client
  45. try:
  46. from urllib.error import HTTPError as compat_HTTPError
  47. except ImportError: # Python 2
  48. from urllib2 import HTTPError as compat_HTTPError
  49. try:
  50. from urllib.request import urlretrieve as compat_urlretrieve
  51. except ImportError: # Python 2
  52. from urllib import urlretrieve as compat_urlretrieve
  53. try:
  54. from subprocess import DEVNULL
  55. compat_subprocess_get_DEVNULL = lambda: DEVNULL
  56. except ImportError:
  57. compat_subprocess_get_DEVNULL = lambda: open(os.path.devnull, 'w')
  58. try:
  59. import http.server as compat_http_server
  60. except ImportError:
  61. import BaseHTTPServer as compat_http_server
  62. try:
  63. from urllib.parse import unquote as compat_urllib_parse_unquote
  64. except ImportError:
  65. def compat_urllib_parse_unquote(string, encoding='utf-8', errors='replace'):
  66. if string == '':
  67. return string
  68. res = string.split('%')
  69. if len(res) == 1:
  70. return string
  71. if encoding is None:
  72. encoding = 'utf-8'
  73. if errors is None:
  74. errors = 'replace'
  75. # pct_sequence: contiguous sequence of percent-encoded bytes, decoded
  76. pct_sequence = b''
  77. string = res[0]
  78. for item in res[1:]:
  79. try:
  80. if not item:
  81. raise ValueError
  82. pct_sequence += item[:2].decode('hex')
  83. rest = item[2:]
  84. if not rest:
  85. # This segment was just a single percent-encoded character.
  86. # May be part of a sequence of code units, so delay decoding.
  87. # (Stored in pct_sequence).
  88. continue
  89. except ValueError:
  90. rest = '%' + item
  91. # Encountered non-percent-encoded characters. Flush the current
  92. # pct_sequence.
  93. string += pct_sequence.decode(encoding, errors) + rest
  94. pct_sequence = b''
  95. if pct_sequence:
  96. # Flush the final pct_sequence
  97. string += pct_sequence.decode(encoding, errors)
  98. return string
  99. try:
  100. compat_str = unicode # Python 2
  101. except NameError:
  102. compat_str = str
  103. try:
  104. compat_basestr = basestring # Python 2
  105. except NameError:
  106. compat_basestr = str
  107. try:
  108. compat_chr = unichr # Python 2
  109. except NameError:
  110. compat_chr = chr
  111. try:
  112. from xml.etree.ElementTree import ParseError as compat_xml_parse_error
  113. except ImportError: # Python 2.6
  114. from xml.parsers.expat import ExpatError as compat_xml_parse_error
  115. try:
  116. from urllib.parse import parse_qs as compat_parse_qs
  117. except ImportError: # Python 2
  118. # HACK: The following is the correct parse_qs implementation from cpython 3's stdlib.
  119. # 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, compat_str
  123. pairs = [s2 for s1 in qs.split('&') for s2 in s1.split(';')]
  124. r = []
  125. for name_value in pairs:
  126. if not name_value and not strict_parsing:
  127. continue
  128. nv = name_value.split('=', 1)
  129. if len(nv) != 2:
  130. if strict_parsing:
  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:
  134. nv.append('')
  135. else:
  136. continue
  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))
  147. return r
  148. def compat_parse_qs(qs, keep_blank_values=False, strict_parsing=False,
  149. encoding='utf-8', errors='replace'):
  150. parsed_result = {}
  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)
  156. else:
  157. parsed_result[name] = [value]
  158. return parsed_result
  159. try:
  160. from shlex import quote as shlex_quote
  161. except ImportError: # Python < 3.3
  162. def shlex_quote(s):
  163. if re.match(r'^[-_\w./]+$', s):
  164. return s
  165. else:
  166. return "'" + s.replace("'", "'\"'\"'") + "'"
  167. def compat_ord(c):
  168. if type(c) is int:
  169. return c
  170. else:
  171. return ord(c)
  172. if sys.version_info >= (3, 0):
  173. compat_getenv = os.getenv
  174. compat_expanduser = os.path.expanduser
  175. else:
  176. # Environment variables should be decoded with filesystem encoding.
  177. # Otherwise it will fail if any non-ASCII characters present (see #3854 #3217 #2918)
  178. def compat_getenv(key, default=None):
  179. from .utils import get_filesystem_encoding
  180. env = os.getenv(key, default)
  181. if env:
  182. env = env.decode(get_filesystem_encoding())
  183. return env
  184. # HACK: The default implementations of os.path.expanduser from cpython do not decode
  185. # environment variables with filesystem encoding. We will work around this by
  186. # providing adjusted implementations.
  187. # The following are os.path.expanduser implementations from cpython 2.7.8 stdlib
  188. # for different platforms with correct environment variables decoding.
  189. if os.name == 'posix':
  190. def compat_expanduser(path):
  191. """Expand ~ and ~user constructions. If user or $HOME is unknown,
  192. do nothing."""
  193. if not path.startswith('~'):
  194. return path
  195. i = path.find('/', 1)
  196. if i < 0:
  197. i = len(path)
  198. if i == 1:
  199. if 'HOME' not in os.environ:
  200. import pwd
  201. userhome = pwd.getpwuid(os.getuid()).pw_dir
  202. else:
  203. userhome = compat_getenv('HOME')
  204. else:
  205. import pwd
  206. try:
  207. pwent = pwd.getpwnam(path[1:i])
  208. except KeyError:
  209. return path
  210. userhome = pwent.pw_dir
  211. userhome = userhome.rstrip('/')
  212. return (userhome + path[i:]) or '/'
  213. elif os.name == 'nt' or os.name == 'ce':
  214. def compat_expanduser(path):
  215. """Expand ~ and ~user constructs.
  216. If user or $HOME is unknown, do nothing."""
  217. if path[:1] != '~':
  218. return path
  219. i, n = 1, len(path)
  220. while i < n and path[i] not in '/\\':
  221. i = i + 1
  222. if 'HOME' in os.environ:
  223. userhome = compat_getenv('HOME')
  224. elif 'USERPROFILE' in os.environ:
  225. userhome = compat_getenv('USERPROFILE')
  226. elif 'HOMEPATH' not in os.environ:
  227. return path
  228. else:
  229. try:
  230. drive = compat_getenv('HOMEDRIVE')
  231. except KeyError:
  232. drive = ''
  233. userhome = os.path.join(drive, compat_getenv('HOMEPATH'))
  234. if i != 1: # ~user
  235. userhome = os.path.join(os.path.dirname(userhome), path[1:i])
  236. return userhome + path[i:]
  237. else:
  238. compat_expanduser = os.path.expanduser
  239. if sys.version_info < (3, 0):
  240. def compat_print(s):
  241. from .utils import preferredencoding
  242. print(s.encode(preferredencoding(), 'xmlcharrefreplace'))
  243. else:
  244. def compat_print(s):
  245. assert isinstance(s, compat_str)
  246. print(s)
  247. try:
  248. subprocess_check_output = subprocess.check_output
  249. except AttributeError:
  250. def subprocess_check_output(*args, **kwargs):
  251. assert 'input' not in kwargs
  252. p = subprocess.Popen(*args, stdout=subprocess.PIPE, **kwargs)
  253. output, _ = p.communicate()
  254. ret = p.poll()
  255. if ret:
  256. raise subprocess.CalledProcessError(ret, p.args, output=output)
  257. return output
  258. if sys.version_info < (3, 0) and sys.platform == 'win32':
  259. def compat_getpass(prompt, *args, **kwargs):
  260. if isinstance(prompt, compat_str):
  261. from .utils import preferredencoding
  262. prompt = prompt.encode(preferredencoding())
  263. return getpass.getpass(prompt, *args, **kwargs)
  264. else:
  265. compat_getpass = getpass.getpass
  266. # Old 2.6 and 2.7 releases require kwargs to be bytes
  267. try:
  268. def _testfunc(x):
  269. pass
  270. _testfunc(**{'x': 0})
  271. except TypeError:
  272. def compat_kwargs(kwargs):
  273. return dict((bytes(k), v) for k, v in kwargs.items())
  274. else:
  275. compat_kwargs = lambda kwargs: kwargs
  276. if sys.version_info < (2, 7):
  277. def compat_socket_create_connection(address, timeout, source_address=None):
  278. host, port = address
  279. err = None
  280. for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  281. af, socktype, proto, canonname, sa = res
  282. sock = None
  283. try:
  284. sock = socket.socket(af, socktype, proto)
  285. sock.settimeout(timeout)
  286. if source_address:
  287. sock.bind(source_address)
  288. sock.connect(sa)
  289. return sock
  290. except socket.error as _:
  291. err = _
  292. if sock is not None:
  293. sock.close()
  294. if err is not None:
  295. raise err
  296. else:
  297. raise socket.error("getaddrinfo returns an empty list")
  298. else:
  299. compat_socket_create_connection = socket.create_connection
  300. # Fix https://github.com/rg3/youtube-dl/issues/4223
  301. # See http://bugs.python.org/issue9161 for what is broken
  302. def workaround_optparse_bug9161():
  303. op = optparse.OptionParser()
  304. og = optparse.OptionGroup(op, 'foo')
  305. try:
  306. og.add_option('-t')
  307. except TypeError:
  308. real_add_option = optparse.OptionGroup.add_option
  309. def _compat_add_option(self, *args, **kwargs):
  310. enc = lambda v: (
  311. v.encode('ascii', 'replace') if isinstance(v, compat_str)
  312. else v)
  313. bargs = [enc(a) for a in args]
  314. bkwargs = dict(
  315. (k, enc(v)) for k, v in kwargs.items())
  316. return real_add_option(self, *bargs, **bkwargs)
  317. optparse.OptionGroup.add_option = _compat_add_option
  318. __all__ = [
  319. 'compat_HTTPError',
  320. 'compat_chr',
  321. 'compat_cookiejar',
  322. 'compat_expanduser',
  323. 'compat_getenv',
  324. 'compat_getpass',
  325. 'compat_html_entities',
  326. 'compat_html_parser',
  327. 'compat_http_client',
  328. 'compat_http_server',
  329. 'compat_kwargs',
  330. 'compat_ord',
  331. 'compat_parse_qs',
  332. 'compat_print',
  333. 'compat_socket_create_connection',
  334. 'compat_str',
  335. 'compat_subprocess_get_DEVNULL',
  336. 'compat_urllib_error',
  337. 'compat_urllib_parse',
  338. 'compat_urllib_parse_unquote',
  339. 'compat_urllib_parse_urlparse',
  340. 'compat_urllib_request',
  341. 'compat_urlparse',
  342. 'compat_urlretrieve',
  343. 'compat_xml_parse_error',
  344. 'shlex_quote',
  345. 'subprocess_check_output',
  346. 'workaround_optparse_bug9161',
  347. ]