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