__init__.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. def compat_shlex_quote(s):
  19. from ..utils import shell_quote
  20. return shell_quote(s)
  21. def compat_ord(c):
  22. return c if isinstance(c, int) else ord(c)
  23. if compat_os_name == 'nt' and sys.version_info < (3, 8):
  24. # os.path.realpath on Windows does not follow symbolic links
  25. # prior to Python 3.8 (see https://bugs.python.org/issue9949)
  26. def compat_realpath(path):
  27. while os.path.islink(path):
  28. path = os.path.abspath(os.readlink(path))
  29. return os.path.realpath(path)
  30. else:
  31. compat_realpath = os.path.realpath
  32. # Python 3.8+ does not honor %HOME% on windows, but this breaks compatibility with youtube-dl
  33. # See https://github.com/yt-dlp/yt-dlp/issues/792
  34. # https://docs.python.org/3/library/os.path.html#os.path.expanduser
  35. if compat_os_name in ('nt', 'ce'):
  36. def compat_expanduser(path):
  37. HOME = os.environ.get('HOME')
  38. if not HOME:
  39. return os.path.expanduser(path)
  40. elif not path.startswith('~'):
  41. return path
  42. i = path.replace('\\', '/', 1).find('/') # ~user
  43. if i < 0:
  44. i = len(path)
  45. userhome = os.path.join(os.path.dirname(HOME), path[1:i]) if i > 1 else HOME
  46. return userhome + path[i:]
  47. else:
  48. compat_expanduser = os.path.expanduser
  49. def urllib_req_to_req(urllib_request):
  50. """Convert urllib Request to a networking Request"""
  51. from ..networking import Request
  52. from ..utils.networking import HTTPHeaderDict
  53. return Request(
  54. urllib_request.get_full_url(), data=urllib_request.data, method=urllib_request.get_method(),
  55. headers=HTTPHeaderDict(urllib_request.headers, urllib_request.unredirected_hdrs),
  56. extensions={'timeout': urllib_request.timeout} if hasattr(urllib_request, 'timeout') else None)