]> jfr.im git - yt-dlp.git/blame - yt_dlp/compat/__init__.py
[ie/brightcove] Upgrade requests to HTTPS (#10202)
[yt-dlp.git] / yt_dlp / compat / __init__.py
CommitLineData
77f90330 1import os
77f90330 2import sys
77f90330 3import xml.etree.ElementTree as etree
4
9196cbfe 5from .compat_utils import passthrough_module
6
a250b247 7passthrough_module(__name__, '._deprecated')
8del passthrough_module
77f90330 9
10
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
0d2a0eca 14class compat_HTMLParseError(ValueError):
77f90330 15 pass
16
17
18class _TreeBuilder(etree.TreeBuilder):
19 def doctype(self, name, pubid, system):
20 pass
21
22
23def compat_etree_fromstring(text):
24 return etree.XML(text, parser=etree.XMLParser(target=_TreeBuilder()))
25
26
27compat_os_name = os._name if os.name == 'java' else os.name
28
29
ff077926
SS
30def compat_shlex_quote(s):
31 from ..utils import shell_quote
32 return shell_quote(s)
77f90330 33
34
35def compat_ord(c):
36 return c if isinstance(c, int) else ord(c)
37
38
77f90330 39if compat_os_name == 'nt' and sys.version_info < (3, 8):
40 # os.path.realpath on Windows does not follow symbolic links
41 # prior to Python 3.8 (see https://bugs.python.org/issue9949)
42 def compat_realpath(path):
43 while os.path.islink(path):
44 path = os.path.abspath(os.readlink(path))
57e0f077 45 return os.path.realpath(path)
77f90330 46else:
47 compat_realpath = os.path.realpath
48
49
77f90330 50# Python 3.8+ does not honor %HOME% on windows, but this breaks compatibility with youtube-dl
51# See https://github.com/yt-dlp/yt-dlp/issues/792
52# https://docs.python.org/3/library/os.path.html#os.path.expanduser
53if compat_os_name in ('nt', 'ce'):
54 def compat_expanduser(path):
55 HOME = os.environ.get('HOME')
56 if not HOME:
57 return os.path.expanduser(path)
58 elif not path.startswith('~'):
59 return path
60 i = path.replace('\\', '/', 1).find('/') # ~user
61 if i < 0:
62 i = len(path)
63 userhome = os.path.join(os.path.dirname(HOME), path[1:i]) if i > 1 else HOME
64 return userhome + path[i:]
65else:
66 compat_expanduser = os.path.expanduser
227bf1a3 67
68
69def urllib_req_to_req(urllib_request):
70 """Convert urllib Request to a networking Request"""
71 from ..networking import Request
72 from ..utils.networking import HTTPHeaderDict
73 return Request(
74 urllib_request.get_full_url(), data=urllib_request.data, method=urllib_request.get_method(),
75 headers=HTTPHeaderDict(urllib_request.headers, urllib_request.unredirected_hdrs),
76 extensions={'timeout': urllib_request.timeout} if hasattr(urllib_request, 'timeout') else None)