__init__.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import os
  2. import sys
  3. import xml.etree.ElementTree as etree
  4. from .compat_utils import passthrough_module
  5. passthrough_module(__name__, '._deprecated')
  6. del passthrough_module
  7. # HTMLParseError has been deprecated in Python 3.3 and removed in
  8. # Python 3.5. Introducing dummy exception for Python >3.5 for compatible
  9. # and uniform cross-version exception handling
  10. class compat_HTMLParseError(ValueError):
  11. pass
  12. class _TreeBuilder(etree.TreeBuilder):
  13. def doctype(self, name, pubid, system):
  14. pass
  15. def compat_etree_fromstring(text):
  16. return etree.XML(text, parser=etree.XMLParser(target=_TreeBuilder()))
  17. compat_os_name = os._name if os.name == 'java' else os.name
  18. if compat_os_name == 'nt':
  19. def compat_shlex_quote(s):
  20. import re
  21. return s if re.match(r'^[-_\w./]+$', s) else '"%s"' % s.replace('"', '\\"')
  22. else:
  23. from shlex import quote as compat_shlex_quote # noqa: F401
  24. def compat_ord(c):
  25. return c if isinstance(c, int) else ord(c)
  26. if compat_os_name == 'nt' and sys.version_info < (3, 8):
  27. # os.path.realpath on Windows does not follow symbolic links
  28. # prior to Python 3.8 (see https://bugs.python.org/issue9949)
  29. def compat_realpath(path):
  30. while os.path.islink(path):
  31. path = os.path.abspath(os.readlink(path))
  32. return os.path.realpath(path)
  33. else:
  34. compat_realpath = os.path.realpath
  35. # Python 3.8+ does not honor %HOME% on windows, but this breaks compatibility with youtube-dl
  36. # See https://github.com/yt-dlp/yt-dlp/issues/792
  37. # https://docs.python.org/3/library/os.path.html#os.path.expanduser
  38. if compat_os_name in ('nt', 'ce'):
  39. def compat_expanduser(path):
  40. HOME = os.environ.get('HOME')
  41. if not HOME:
  42. return os.path.expanduser(path)
  43. elif not path.startswith('~'):
  44. return path
  45. i = path.replace('\\', '/', 1).find('/') # ~user
  46. if i < 0:
  47. i = len(path)
  48. userhome = os.path.join(os.path.dirname(HOME), path[1:i]) if i > 1 else HOME
  49. return userhome + path[i:]
  50. else:
  51. compat_expanduser = os.path.expanduser
  52. def urllib_req_to_req(urllib_request):
  53. """Convert urllib Request to a networking Request"""
  54. from ..networking import Request
  55. from ..utils.networking import HTTPHeaderDict
  56. return Request(
  57. urllib_request.get_full_url(), data=urllib_request.data, method=urllib_request.get_method(),
  58. headers=HTTPHeaderDict(urllib_request.headers, urllib_request.unredirected_hdrs),
  59. extensions={'timeout': urllib_request.timeout} if hasattr(urllib_request, 'timeout') else None)