__init__.py 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. try:
  2. import contextvars # noqa: F401
  3. except Exception:
  4. raise Exception(
  5. f'You are using an unsupported version of Python. Only Python versions 3.7 and above are supported by yt-dlp') # noqa: F541
  6. __license__ = 'Public Domain'
  7. import collections
  8. import getpass
  9. import itertools
  10. import optparse
  11. import os
  12. import re
  13. import sys
  14. import traceback
  15. from .compat import compat_shlex_quote
  16. from .cookies import SUPPORTED_BROWSERS, SUPPORTED_KEYRINGS
  17. from .downloader.external import get_external_downloader
  18. from .extractor import list_extractor_classes
  19. from .extractor.adobepass import MSO_INFO
  20. from .options import parseOpts
  21. from .postprocessor import (
  22. FFmpegExtractAudioPP,
  23. FFmpegMergerPP,
  24. FFmpegPostProcessor,
  25. FFmpegSubtitlesConvertorPP,
  26. FFmpegThumbnailsConvertorPP,
  27. FFmpegVideoConvertorPP,
  28. FFmpegVideoRemuxerPP,
  29. MetadataFromFieldPP,
  30. MetadataParserPP,
  31. )
  32. from .update import Updater
  33. from .utils import (
  34. NO_DEFAULT,
  35. POSTPROCESS_WHEN,
  36. DateRange,
  37. DownloadCancelled,
  38. DownloadError,
  39. FormatSorter,
  40. GeoUtils,
  41. PlaylistEntries,
  42. SameFileError,
  43. decodeOption,
  44. download_range_func,
  45. expand_path,
  46. float_or_none,
  47. format_field,
  48. int_or_none,
  49. match_filter_func,
  50. parse_bytes,
  51. parse_duration,
  52. preferredencoding,
  53. read_batch_urls,
  54. read_stdin,
  55. render_table,
  56. setproctitle,
  57. traverse_obj,
  58. variadic,
  59. write_string,
  60. )
  61. from .utils.networking import std_headers
  62. from .YoutubeDL import YoutubeDL
  63. _IN_CLI = False
  64. def _exit(status=0, *args):
  65. for msg in args:
  66. sys.stderr.write(msg)
  67. raise SystemExit(status)
  68. def get_urls(urls, batchfile, verbose):
  69. # Batch file verification
  70. batch_urls = []
  71. if batchfile is not None:
  72. try:
  73. batch_urls = read_batch_urls(
  74. read_stdin('URLs') if batchfile == '-'
  75. else open(expand_path(batchfile), encoding='utf-8', errors='ignore'))
  76. if verbose:
  77. write_string('[debug] Batch file urls: ' + repr(batch_urls) + '\n')
  78. except OSError:
  79. _exit(f'ERROR: batch file {batchfile} could not be read')
  80. _enc = preferredencoding()
  81. return [
  82. url.strip().decode(_enc, 'ignore') if isinstance(url, bytes) else url.strip()
  83. for url in batch_urls + urls]
  84. def print_extractor_information(opts, urls):
  85. out = ''
  86. if opts.list_extractors:
  87. # Importing GenericIE is currently slow since it imports YoutubeIE
  88. from .extractor.generic import GenericIE
  89. urls = dict.fromkeys(urls, False)
  90. for ie in list_extractor_classes(opts.age_limit):
  91. out += ie.IE_NAME + (' (CURRENTLY BROKEN)' if not ie.working() else '') + '\n'
  92. if ie == GenericIE:
  93. matched_urls = [url for url, matched in urls.items() if not matched]
  94. else:
  95. matched_urls = tuple(filter(ie.suitable, urls.keys()))
  96. urls.update(dict.fromkeys(matched_urls, True))
  97. out += ''.join(f' {url}\n' for url in matched_urls)
  98. elif opts.list_extractor_descriptions:
  99. _SEARCHES = ('cute kittens', 'slithering pythons', 'falling cat', 'angry poodle', 'purple fish', 'running tortoise', 'sleeping bunny', 'burping cow')
  100. out = '\n'.join(
  101. ie.description(markdown=False, search_examples=_SEARCHES)
  102. for ie in list_extractor_classes(opts.age_limit) if ie.working() and ie.IE_DESC is not False)
  103. elif opts.ap_list_mso:
  104. out = 'Supported TV Providers:\n%s\n' % render_table(
  105. ['mso', 'mso name'],
  106. [[mso_id, mso_info['name']] for mso_id, mso_info in MSO_INFO.items()])
  107. else:
  108. return False
  109. write_string(out, out=sys.stdout)
  110. return True
  111. def set_compat_opts(opts):
  112. def _unused_compat_opt(name):
  113. if name not in opts.compat_opts:
  114. return False
  115. opts.compat_opts.discard(name)
  116. opts.compat_opts.update(['*%s' % name])
  117. return True
  118. def set_default_compat(compat_name, opt_name, default=True, remove_compat=True):
  119. attr = getattr(opts, opt_name)
  120. if compat_name in opts.compat_opts:
  121. if attr is None:
  122. setattr(opts, opt_name, not default)
  123. return True
  124. else:
  125. if remove_compat:
  126. _unused_compat_opt(compat_name)
  127. return False
  128. elif attr is None:
  129. setattr(opts, opt_name, default)
  130. return None
  131. set_default_compat('abort-on-error', 'ignoreerrors', 'only_download')
  132. set_default_compat('no-playlist-metafiles', 'allow_playlist_files')
  133. set_default_compat('no-clean-infojson', 'clean_infojson')
  134. if 'no-attach-info-json' in opts.compat_opts:
  135. if opts.embed_infojson:
  136. _unused_compat_opt('no-attach-info-json')
  137. else:
  138. opts.embed_infojson = False
  139. if 'format-sort' in opts.compat_opts:
  140. opts.format_sort.extend(FormatSorter.ytdl_default)
  141. _video_multistreams_set = set_default_compat('multistreams', 'allow_multiple_video_streams', False, remove_compat=False)
  142. _audio_multistreams_set = set_default_compat('multistreams', 'allow_multiple_audio_streams', False, remove_compat=False)
  143. if _video_multistreams_set is False and _audio_multistreams_set is False:
  144. _unused_compat_opt('multistreams')
  145. if 'filename' in opts.compat_opts:
  146. if opts.outtmpl.get('default') is None:
  147. opts.outtmpl.update({'default': '%(title)s-%(id)s.%(ext)s'})
  148. else:
  149. _unused_compat_opt('filename')
  150. def validate_options(opts):
  151. def validate(cndn, name, value=None, msg=None):
  152. if cndn:
  153. return True
  154. raise ValueError((msg or 'invalid {name} "{value}" given').format(name=name, value=value))
  155. def validate_in(name, value, items, msg=None):
  156. return validate(value is None or value in items, name, value, msg)
  157. def validate_regex(name, value, regex):
  158. return validate(value is None or re.match(regex, value), name, value)
  159. def validate_positive(name, value, strict=False):
  160. return validate(value is None or value > 0 or (not strict and value == 0),
  161. name, value, '{name} "{value}" must be positive' + ('' if strict else ' or 0'))
  162. def validate_minmax(min_val, max_val, min_name, max_name=None):
  163. if max_val is None or min_val is None or max_val >= min_val:
  164. return
  165. if not max_name:
  166. min_name, max_name = f'min {min_name}', f'max {min_name}'
  167. raise ValueError(f'{max_name} "{max_val}" must be must be greater than or equal to {min_name} "{min_val}"')
  168. # Usernames and passwords
  169. validate(sum(map(bool, (opts.usenetrc, opts.netrc_cmd, opts.username))) <= 1, '.netrc',
  170. msg='{name}, netrc command and username/password are mutually exclusive options')
  171. validate(opts.password is None or opts.username is not None, 'account username', msg='{name} missing')
  172. validate(opts.ap_password is None or opts.ap_username is not None,
  173. 'TV Provider account username', msg='{name} missing')
  174. validate_in('TV Provider', opts.ap_mso, MSO_INFO,
  175. 'Unsupported {name} "{value}", use --ap-list-mso to get a list of supported TV Providers')
  176. # Numbers
  177. validate_positive('autonumber start', opts.autonumber_start)
  178. validate_positive('autonumber size', opts.autonumber_size, True)
  179. validate_positive('concurrent fragments', opts.concurrent_fragment_downloads, True)
  180. validate_positive('playlist start', opts.playliststart, True)
  181. if opts.playlistend != -1:
  182. validate_minmax(opts.playliststart, opts.playlistend, 'playlist start', 'playlist end')
  183. # Time ranges
  184. validate_positive('subtitles sleep interval', opts.sleep_interval_subtitles)
  185. validate_positive('requests sleep interval', opts.sleep_interval_requests)
  186. validate_positive('sleep interval', opts.sleep_interval)
  187. validate_positive('max sleep interval', opts.max_sleep_interval)
  188. if opts.sleep_interval is None:
  189. validate(
  190. opts.max_sleep_interval is None, 'min sleep interval',
  191. msg='{name} must be specified; use --min-sleep-interval')
  192. elif opts.max_sleep_interval is None:
  193. opts.max_sleep_interval = opts.sleep_interval
  194. else:
  195. validate_minmax(opts.sleep_interval, opts.max_sleep_interval, 'sleep interval')
  196. if opts.wait_for_video is not None:
  197. min_wait, max_wait, *_ = map(parse_duration, opts.wait_for_video.split('-', 1) + [None])
  198. validate(min_wait is not None and not (max_wait is None and '-' in opts.wait_for_video),
  199. 'time range to wait for video', opts.wait_for_video)
  200. validate_minmax(min_wait, max_wait, 'time range to wait for video')
  201. opts.wait_for_video = (min_wait, max_wait)
  202. # Format sort
  203. for f in opts.format_sort:
  204. validate_regex('format sorting', f, FormatSorter.regex)
  205. # Postprocessor formats
  206. validate_regex('merge output format', opts.merge_output_format,
  207. r'({0})(/({0}))*'.format('|'.join(map(re.escape, FFmpegMergerPP.SUPPORTED_EXTS))))
  208. validate_regex('audio format', opts.audioformat, FFmpegExtractAudioPP.FORMAT_RE)
  209. validate_in('subtitle format', opts.convertsubtitles, FFmpegSubtitlesConvertorPP.SUPPORTED_EXTS)
  210. validate_regex('thumbnail format', opts.convertthumbnails, FFmpegThumbnailsConvertorPP.FORMAT_RE)
  211. validate_regex('recode video format', opts.recodevideo, FFmpegVideoConvertorPP.FORMAT_RE)
  212. validate_regex('remux video format', opts.remuxvideo, FFmpegVideoRemuxerPP.FORMAT_RE)
  213. if opts.audioquality:
  214. opts.audioquality = opts.audioquality.strip('k').strip('K')
  215. # int_or_none prevents inf, nan
  216. validate_positive('audio quality', int_or_none(float_or_none(opts.audioquality), default=0))
  217. # Retries
  218. def parse_retries(name, value):
  219. if value is None:
  220. return None
  221. elif value in ('inf', 'infinite'):
  222. return float('inf')
  223. try:
  224. return int(value)
  225. except (TypeError, ValueError):
  226. validate(False, f'{name} retry count', value)
  227. opts.retries = parse_retries('download', opts.retries)
  228. opts.fragment_retries = parse_retries('fragment', opts.fragment_retries)
  229. opts.extractor_retries = parse_retries('extractor', opts.extractor_retries)
  230. opts.file_access_retries = parse_retries('file access', opts.file_access_retries)
  231. # Retry sleep function
  232. def parse_sleep_func(expr):
  233. NUMBER_RE = r'\d+(?:\.\d+)?'
  234. op, start, limit, step, *_ = tuple(re.fullmatch(
  235. rf'(?:(linear|exp)=)?({NUMBER_RE})(?::({NUMBER_RE})?)?(?::({NUMBER_RE}))?',
  236. expr.strip()).groups()) + (None, None)
  237. if op == 'exp':
  238. return lambda n: min(float(start) * (float(step or 2) ** n), float(limit or 'inf'))
  239. else:
  240. default_step = start if op or limit else 0
  241. return lambda n: min(float(start) + float(step or default_step) * n, float(limit or 'inf'))
  242. for key, expr in opts.retry_sleep.items():
  243. if not expr:
  244. del opts.retry_sleep[key]
  245. continue
  246. try:
  247. opts.retry_sleep[key] = parse_sleep_func(expr)
  248. except AttributeError:
  249. raise ValueError(f'invalid {key} retry sleep expression {expr!r}')
  250. # Bytes
  251. def validate_bytes(name, value):
  252. if value is None:
  253. return None
  254. numeric_limit = parse_bytes(value)
  255. validate(numeric_limit is not None, 'rate limit', value)
  256. return numeric_limit
  257. opts.ratelimit = validate_bytes('rate limit', opts.ratelimit)
  258. opts.throttledratelimit = validate_bytes('throttled rate limit', opts.throttledratelimit)
  259. opts.min_filesize = validate_bytes('min filesize', opts.min_filesize)
  260. opts.max_filesize = validate_bytes('max filesize', opts.max_filesize)
  261. opts.buffersize = validate_bytes('buffer size', opts.buffersize)
  262. opts.http_chunk_size = validate_bytes('http chunk size', opts.http_chunk_size)
  263. # Output templates
  264. def validate_outtmpl(tmpl, msg):
  265. err = YoutubeDL.validate_outtmpl(tmpl)
  266. if err:
  267. raise ValueError(f'invalid {msg} "{tmpl}": {err}')
  268. for k, tmpl in opts.outtmpl.items():
  269. validate_outtmpl(tmpl, f'{k} output template')
  270. for type_, tmpl_list in opts.forceprint.items():
  271. for tmpl in tmpl_list:
  272. validate_outtmpl(tmpl, f'{type_} print template')
  273. for type_, tmpl_list in opts.print_to_file.items():
  274. for tmpl, file in tmpl_list:
  275. validate_outtmpl(tmpl, f'{type_} print to file template')
  276. validate_outtmpl(file, f'{type_} print to file filename')
  277. validate_outtmpl(opts.sponsorblock_chapter_title, 'SponsorBlock chapter title')
  278. for k, tmpl in opts.progress_template.items():
  279. k = f'{k[:-6]} console title' if '-title' in k else f'{k} progress'
  280. validate_outtmpl(tmpl, f'{k} template')
  281. outtmpl_default = opts.outtmpl.get('default')
  282. if outtmpl_default == '':
  283. opts.skip_download = None
  284. del opts.outtmpl['default']
  285. def parse_chapters(name, value, advanced=False):
  286. parse_timestamp = lambda x: float('inf') if x in ('inf', 'infinite') else parse_duration(x)
  287. TIMESTAMP_RE = r'''(?x)(?:
  288. (?P<start_sign>-?)(?P<start>[^-]+)
  289. )?\s*-\s*(?:
  290. (?P<end_sign>-?)(?P<end>[^-]+)
  291. )?'''
  292. chapters, ranges, from_url = [], [], False
  293. for regex in value or []:
  294. if advanced and regex == '*from-url':
  295. from_url = True
  296. continue
  297. elif not regex.startswith('*'):
  298. try:
  299. chapters.append(re.compile(regex))
  300. except re.error as err:
  301. raise ValueError(f'invalid {name} regex "{regex}" - {err}')
  302. continue
  303. for range_ in map(str.strip, regex[1:].split(',')):
  304. mobj = range_ != '-' and re.fullmatch(TIMESTAMP_RE, range_)
  305. dur = mobj and [parse_timestamp(mobj.group('start') or '0'), parse_timestamp(mobj.group('end') or 'inf')]
  306. signs = mobj and (mobj.group('start_sign'), mobj.group('end_sign'))
  307. err = None
  308. if None in (dur or [None]):
  309. err = 'Must be of the form "*start-end"'
  310. elif not advanced and any(signs):
  311. err = 'Negative timestamps are not allowed'
  312. else:
  313. dur[0] *= -1 if signs[0] else 1
  314. dur[1] *= -1 if signs[1] else 1
  315. if dur[1] == float('-inf'):
  316. err = '"-inf" is not a valid end'
  317. if err:
  318. raise ValueError(f'invalid {name} time range "{regex}". {err}')
  319. ranges.append(dur)
  320. return chapters, ranges, from_url
  321. opts.remove_chapters, opts.remove_ranges, _ = parse_chapters('--remove-chapters', opts.remove_chapters)
  322. opts.download_ranges = download_range_func(*parse_chapters('--download-sections', opts.download_ranges, True))
  323. # Cookies from browser
  324. if opts.cookiesfrombrowser:
  325. container = None
  326. mobj = re.fullmatch(r'''(?x)
  327. (?P<name>[^+:]+)
  328. (?:\s*\+\s*(?P<keyring>[^:]+))?
  329. (?:\s*:\s*(?!:)(?P<profile>.+?))?
  330. (?:\s*::\s*(?P<container>.+))?
  331. ''', opts.cookiesfrombrowser)
  332. if mobj is None:
  333. raise ValueError(f'invalid cookies from browser arguments: {opts.cookiesfrombrowser}')
  334. browser_name, keyring, profile, container = mobj.group('name', 'keyring', 'profile', 'container')
  335. browser_name = browser_name.lower()
  336. if browser_name not in SUPPORTED_BROWSERS:
  337. raise ValueError(f'unsupported browser specified for cookies: "{browser_name}". '
  338. f'Supported browsers are: {", ".join(sorted(SUPPORTED_BROWSERS))}')
  339. if keyring is not None:
  340. keyring = keyring.upper()
  341. if keyring not in SUPPORTED_KEYRINGS:
  342. raise ValueError(f'unsupported keyring specified for cookies: "{keyring}". '
  343. f'Supported keyrings are: {", ".join(sorted(SUPPORTED_KEYRINGS))}')
  344. opts.cookiesfrombrowser = (browser_name, profile, keyring, container)
  345. # MetadataParser
  346. def metadataparser_actions(f):
  347. if isinstance(f, str):
  348. cmd = '--parse-metadata %s' % compat_shlex_quote(f)
  349. try:
  350. actions = [MetadataFromFieldPP.to_action(f)]
  351. except Exception as err:
  352. raise ValueError(f'{cmd} is invalid; {err}')
  353. else:
  354. cmd = '--replace-in-metadata %s' % ' '.join(map(compat_shlex_quote, f))
  355. actions = ((MetadataParserPP.Actions.REPLACE, x, *f[1:]) for x in f[0].split(','))
  356. for action in actions:
  357. try:
  358. MetadataParserPP.validate_action(*action)
  359. except Exception as err:
  360. raise ValueError(f'{cmd} is invalid; {err}')
  361. yield action
  362. if opts.metafromtitle is not None:
  363. opts.parse_metadata.setdefault('pre_process', []).append('title:%s' % opts.metafromtitle)
  364. opts.parse_metadata = {
  365. k: list(itertools.chain(*map(metadataparser_actions, v)))
  366. for k, v in opts.parse_metadata.items()
  367. }
  368. # Other options
  369. if opts.playlist_items is not None:
  370. try:
  371. tuple(PlaylistEntries.parse_playlist_items(opts.playlist_items))
  372. except Exception as err:
  373. raise ValueError(f'Invalid playlist-items {opts.playlist_items!r}: {err}')
  374. opts.geo_bypass_country, opts.geo_bypass_ip_block = None, None
  375. if opts.geo_bypass.lower() not in ('default', 'never'):
  376. try:
  377. GeoUtils.random_ipv4(opts.geo_bypass)
  378. except Exception:
  379. raise ValueError(f'Unsupported --xff "{opts.geo_bypass}"')
  380. if len(opts.geo_bypass) == 2:
  381. opts.geo_bypass_country = opts.geo_bypass
  382. else:
  383. opts.geo_bypass_ip_block = opts.geo_bypass
  384. opts.geo_bypass = opts.geo_bypass.lower() != 'never'
  385. opts.match_filter = match_filter_func(opts.match_filter, opts.breaking_match_filter)
  386. if opts.download_archive is not None:
  387. opts.download_archive = expand_path(opts.download_archive)
  388. if opts.ffmpeg_location is not None:
  389. opts.ffmpeg_location = expand_path(opts.ffmpeg_location)
  390. if opts.user_agent is not None:
  391. opts.headers.setdefault('User-Agent', opts.user_agent)
  392. if opts.referer is not None:
  393. opts.headers.setdefault('Referer', opts.referer)
  394. if opts.no_sponsorblock:
  395. opts.sponsorblock_mark = opts.sponsorblock_remove = set()
  396. default_downloader = None
  397. for proto, path in opts.external_downloader.items():
  398. if path == 'native':
  399. continue
  400. ed = get_external_downloader(path)
  401. if ed is None:
  402. raise ValueError(
  403. f'No such {format_field(proto, None, "%s ", ignore="default")}external downloader "{path}"')
  404. elif ed and proto == 'default':
  405. default_downloader = ed.get_basename()
  406. for policy in opts.color.values():
  407. if policy not in ('always', 'auto', 'no_color', 'never'):
  408. raise ValueError(f'"{policy}" is not a valid color policy')
  409. warnings, deprecation_warnings = [], []
  410. # Common mistake: -f best
  411. if opts.format == 'best':
  412. warnings.append('.\n '.join((
  413. '"-f best" selects the best pre-merged format which is often not the best option',
  414. 'To let yt-dlp download and merge the best available formats, simply do not pass any format selection',
  415. 'If you know what you are doing and want only the best pre-merged format, use "-f b" instead to suppress this warning')))
  416. # --(postprocessor/downloader)-args without name
  417. def report_args_compat(name, value, key1, key2=None, where=None):
  418. if key1 in value and key2 not in value:
  419. warnings.append(f'{name.title()} arguments given without specifying name. '
  420. f'The arguments will be given to {where or f"all {name}s"}')
  421. return True
  422. return False
  423. if report_args_compat('external downloader', opts.external_downloader_args,
  424. 'default', where=default_downloader) and default_downloader:
  425. # Compat with youtube-dl's behavior. See https://github.com/ytdl-org/youtube-dl/commit/49c5293014bc11ec8c009856cd63cffa6296c1e1
  426. opts.external_downloader_args.setdefault(default_downloader, opts.external_downloader_args.pop('default'))
  427. if report_args_compat('post-processor', opts.postprocessor_args, 'default-compat', 'default'):
  428. opts.postprocessor_args['default'] = opts.postprocessor_args.pop('default-compat')
  429. opts.postprocessor_args.setdefault('sponskrub', [])
  430. def report_conflict(arg1, opt1, arg2='--allow-unplayable-formats', opt2='allow_unplayable_formats',
  431. val1=NO_DEFAULT, val2=NO_DEFAULT, default=False):
  432. if val2 is NO_DEFAULT:
  433. val2 = getattr(opts, opt2)
  434. if not val2:
  435. return
  436. if val1 is NO_DEFAULT:
  437. val1 = getattr(opts, opt1)
  438. if val1:
  439. warnings.append(f'{arg1} is ignored since {arg2} was given')
  440. setattr(opts, opt1, default)
  441. # Conflicting options
  442. report_conflict('--playlist-reverse', 'playlist_reverse', '--playlist-random', 'playlist_random')
  443. report_conflict('--playlist-reverse', 'playlist_reverse', '--lazy-playlist', 'lazy_playlist')
  444. report_conflict('--playlist-random', 'playlist_random', '--lazy-playlist', 'lazy_playlist')
  445. report_conflict('--dateafter', 'dateafter', '--date', 'date', default=None)
  446. report_conflict('--datebefore', 'datebefore', '--date', 'date', default=None)
  447. report_conflict('--exec-before-download', 'exec_before_dl_cmd',
  448. '"--exec before_dl:"', 'exec_cmd', val2=opts.exec_cmd.get('before_dl'))
  449. report_conflict('--id', 'useid', '--output', 'outtmpl', val2=opts.outtmpl.get('default'))
  450. report_conflict('--remux-video', 'remuxvideo', '--recode-video', 'recodevideo')
  451. report_conflict('--sponskrub', 'sponskrub', '--remove-chapters', 'remove_chapters')
  452. report_conflict('--sponskrub', 'sponskrub', '--sponsorblock-mark', 'sponsorblock_mark')
  453. report_conflict('--sponskrub', 'sponskrub', '--sponsorblock-remove', 'sponsorblock_remove')
  454. report_conflict('--sponskrub-cut', 'sponskrub_cut', '--split-chapter', 'split_chapters',
  455. val1=opts.sponskrub and opts.sponskrub_cut)
  456. # Conflicts with --allow-unplayable-formats
  457. report_conflict('--embed-metadata', 'addmetadata')
  458. report_conflict('--embed-chapters', 'addchapters')
  459. report_conflict('--embed-info-json', 'embed_infojson')
  460. report_conflict('--embed-subs', 'embedsubtitles')
  461. report_conflict('--embed-thumbnail', 'embedthumbnail')
  462. report_conflict('--extract-audio', 'extractaudio')
  463. report_conflict('--fixup', 'fixup', val1=opts.fixup not in (None, 'never', 'ignore'), default='never')
  464. report_conflict('--recode-video', 'recodevideo')
  465. report_conflict('--remove-chapters', 'remove_chapters', default=[])
  466. report_conflict('--remux-video', 'remuxvideo')
  467. report_conflict('--sponskrub', 'sponskrub')
  468. report_conflict('--sponsorblock-remove', 'sponsorblock_remove', default=set())
  469. report_conflict('--xattrs', 'xattrs')
  470. # Fully deprecated options
  471. def report_deprecation(val, old, new=None):
  472. if not val:
  473. return
  474. deprecation_warnings.append(
  475. f'{old} is deprecated and may be removed in a future version. Use {new} instead' if new
  476. else f'{old} is deprecated and may not work as expected')
  477. report_deprecation(opts.sponskrub, '--sponskrub', '--sponsorblock-mark or --sponsorblock-remove')
  478. report_deprecation(not opts.prefer_ffmpeg, '--prefer-avconv', 'ffmpeg')
  479. # report_deprecation(opts.include_ads, '--include-ads') # We may re-implement this in future
  480. # report_deprecation(opts.call_home, '--call-home') # We may re-implement this in future
  481. # report_deprecation(opts.writeannotations, '--write-annotations') # It's just that no website has it
  482. # Dependent options
  483. opts.date = DateRange.day(opts.date) if opts.date else DateRange(opts.dateafter, opts.datebefore)
  484. if opts.exec_before_dl_cmd:
  485. opts.exec_cmd['before_dl'] = opts.exec_before_dl_cmd
  486. if opts.useid: # --id is not deprecated in youtube-dl
  487. opts.outtmpl['default'] = '%(id)s.%(ext)s'
  488. if opts.overwrites: # --force-overwrites implies --no-continue
  489. opts.continue_dl = False
  490. if (opts.addmetadata or opts.sponsorblock_mark) and opts.addchapters is None:
  491. # Add chapters when adding metadata or marking sponsors
  492. opts.addchapters = True
  493. if opts.extractaudio and not opts.keepvideo and opts.format is None:
  494. # Do not unnecessarily download audio
  495. opts.format = 'bestaudio/best'
  496. if opts.getcomments and opts.writeinfojson is None and not opts.embed_infojson:
  497. # If JSON is not printed anywhere, but comments are requested, save it to file
  498. if not opts.dumpjson or opts.print_json or opts.dump_single_json:
  499. opts.writeinfojson = True
  500. if opts.allsubtitles and not (opts.embedsubtitles or opts.writeautomaticsub):
  501. # --all-sub automatically sets --write-sub if --write-auto-sub is not given
  502. opts.writesubtitles = True
  503. if opts.addmetadata and opts.embed_infojson is None:
  504. # If embedding metadata and infojson is present, embed it
  505. opts.embed_infojson = 'if_exists'
  506. # Ask for passwords
  507. if opts.username is not None and opts.password is None:
  508. opts.password = getpass.getpass('Type account password and press [Return]: ')
  509. if opts.ap_username is not None and opts.ap_password is None:
  510. opts.ap_password = getpass.getpass('Type TV provider account password and press [Return]: ')
  511. return warnings, deprecation_warnings
  512. def get_postprocessors(opts):
  513. yield from opts.add_postprocessors
  514. for when, actions in opts.parse_metadata.items():
  515. yield {
  516. 'key': 'MetadataParser',
  517. 'actions': actions,
  518. 'when': when
  519. }
  520. sponsorblock_query = opts.sponsorblock_mark | opts.sponsorblock_remove
  521. if sponsorblock_query:
  522. yield {
  523. 'key': 'SponsorBlock',
  524. 'categories': sponsorblock_query,
  525. 'api': opts.sponsorblock_api,
  526. 'when': 'after_filter'
  527. }
  528. if opts.convertsubtitles:
  529. yield {
  530. 'key': 'FFmpegSubtitlesConvertor',
  531. 'format': opts.convertsubtitles,
  532. 'when': 'before_dl'
  533. }
  534. if opts.convertthumbnails:
  535. yield {
  536. 'key': 'FFmpegThumbnailsConvertor',
  537. 'format': opts.convertthumbnails,
  538. 'when': 'before_dl'
  539. }
  540. if opts.extractaudio:
  541. yield {
  542. 'key': 'FFmpegExtractAudio',
  543. 'preferredcodec': opts.audioformat,
  544. 'preferredquality': opts.audioquality,
  545. 'nopostoverwrites': opts.nopostoverwrites,
  546. }
  547. if opts.remuxvideo:
  548. yield {
  549. 'key': 'FFmpegVideoRemuxer',
  550. 'preferedformat': opts.remuxvideo,
  551. }
  552. if opts.recodevideo:
  553. yield {
  554. 'key': 'FFmpegVideoConvertor',
  555. 'preferedformat': opts.recodevideo,
  556. }
  557. # If ModifyChapters is going to remove chapters, subtitles must already be in the container.
  558. if opts.embedsubtitles:
  559. keep_subs = 'no-keep-subs' not in opts.compat_opts
  560. yield {
  561. 'key': 'FFmpegEmbedSubtitle',
  562. # already_have_subtitle = True prevents the file from being deleted after embedding
  563. 'already_have_subtitle': opts.writesubtitles and keep_subs
  564. }
  565. if not opts.writeautomaticsub and keep_subs:
  566. opts.writesubtitles = True
  567. # ModifyChapters must run before FFmpegMetadataPP
  568. if opts.remove_chapters or sponsorblock_query:
  569. yield {
  570. 'key': 'ModifyChapters',
  571. 'remove_chapters_patterns': opts.remove_chapters,
  572. 'remove_sponsor_segments': opts.sponsorblock_remove,
  573. 'remove_ranges': opts.remove_ranges,
  574. 'sponsorblock_chapter_title': opts.sponsorblock_chapter_title,
  575. 'force_keyframes': opts.force_keyframes_at_cuts
  576. }
  577. # FFmpegMetadataPP should be run after FFmpegVideoConvertorPP and
  578. # FFmpegExtractAudioPP as containers before conversion may not support
  579. # metadata (3gp, webm, etc.)
  580. # By default ffmpeg preserves metadata applicable for both
  581. # source and target containers. From this point the container won't change,
  582. # so metadata can be added here.
  583. if opts.addmetadata or opts.addchapters or opts.embed_infojson:
  584. yield {
  585. 'key': 'FFmpegMetadata',
  586. 'add_chapters': opts.addchapters,
  587. 'add_metadata': opts.addmetadata,
  588. 'add_infojson': opts.embed_infojson,
  589. }
  590. # Deprecated
  591. # This should be above EmbedThumbnail since sponskrub removes the thumbnail attachment
  592. # but must be below EmbedSubtitle and FFmpegMetadata
  593. # See https://github.com/yt-dlp/yt-dlp/issues/204 , https://github.com/faissaloo/SponSkrub/issues/29
  594. # If opts.sponskrub is None, sponskrub is used, but it silently fails if the executable can't be found
  595. if opts.sponskrub is not False:
  596. yield {
  597. 'key': 'SponSkrub',
  598. 'path': opts.sponskrub_path,
  599. 'args': opts.sponskrub_args,
  600. 'cut': opts.sponskrub_cut,
  601. 'force': opts.sponskrub_force,
  602. 'ignoreerror': opts.sponskrub is None,
  603. '_from_cli': True,
  604. }
  605. if opts.embedthumbnail:
  606. yield {
  607. 'key': 'EmbedThumbnail',
  608. # already_have_thumbnail = True prevents the file from being deleted after embedding
  609. 'already_have_thumbnail': opts.writethumbnail
  610. }
  611. if not opts.writethumbnail:
  612. opts.writethumbnail = True
  613. opts.outtmpl['pl_thumbnail'] = ''
  614. if opts.split_chapters:
  615. yield {
  616. 'key': 'FFmpegSplitChapters',
  617. 'force_keyframes': opts.force_keyframes_at_cuts,
  618. }
  619. # XAttrMetadataPP should be run after post-processors that may change file contents
  620. if opts.xattrs:
  621. yield {'key': 'XAttrMetadata'}
  622. if opts.concat_playlist != 'never':
  623. yield {
  624. 'key': 'FFmpegConcat',
  625. 'only_multi_video': opts.concat_playlist != 'always',
  626. 'when': 'playlist',
  627. }
  628. # Exec must be the last PP of each category
  629. for when, exec_cmd in opts.exec_cmd.items():
  630. yield {
  631. 'key': 'Exec',
  632. 'exec_cmd': exec_cmd,
  633. 'when': when,
  634. }
  635. ParsedOptions = collections.namedtuple('ParsedOptions', ('parser', 'options', 'urls', 'ydl_opts'))
  636. def parse_options(argv=None):
  637. """@returns ParsedOptions(parser, opts, urls, ydl_opts)"""
  638. parser, opts, urls = parseOpts(argv)
  639. urls = get_urls(urls, opts.batchfile, opts.verbose)
  640. set_compat_opts(opts)
  641. try:
  642. warnings, deprecation_warnings = validate_options(opts)
  643. except ValueError as err:
  644. parser.error(f'{err}\n')
  645. postprocessors = list(get_postprocessors(opts))
  646. print_only = bool(opts.forceprint) and all(k not in opts.forceprint for k in POSTPROCESS_WHEN[3:])
  647. any_getting = any(getattr(opts, k) for k in (
  648. 'dumpjson', 'dump_single_json', 'getdescription', 'getduration', 'getfilename',
  649. 'getformat', 'getid', 'getthumbnail', 'gettitle', 'geturl'
  650. ))
  651. if opts.quiet is None:
  652. opts.quiet = any_getting or opts.print_json or bool(opts.forceprint)
  653. playlist_pps = [pp for pp in postprocessors if pp.get('when') == 'playlist']
  654. write_playlist_infojson = (opts.writeinfojson and not opts.clean_infojson
  655. and opts.allow_playlist_files and opts.outtmpl.get('pl_infojson') != '')
  656. if not any((
  657. opts.extract_flat,
  658. opts.dump_single_json,
  659. opts.forceprint.get('playlist'),
  660. opts.print_to_file.get('playlist'),
  661. write_playlist_infojson,
  662. )):
  663. if not playlist_pps:
  664. opts.extract_flat = 'discard'
  665. elif playlist_pps == [{'key': 'FFmpegConcat', 'only_multi_video': True, 'when': 'playlist'}]:
  666. opts.extract_flat = 'discard_in_playlist'
  667. final_ext = (
  668. opts.recodevideo if opts.recodevideo in FFmpegVideoConvertorPP.SUPPORTED_EXTS
  669. else opts.remuxvideo if opts.remuxvideo in FFmpegVideoRemuxerPP.SUPPORTED_EXTS
  670. else opts.audioformat if (opts.extractaudio and opts.audioformat in FFmpegExtractAudioPP.SUPPORTED_EXTS)
  671. else None)
  672. return ParsedOptions(parser, opts, urls, {
  673. 'usenetrc': opts.usenetrc,
  674. 'netrc_location': opts.netrc_location,
  675. 'netrc_cmd': opts.netrc_cmd,
  676. 'username': opts.username,
  677. 'password': opts.password,
  678. 'twofactor': opts.twofactor,
  679. 'videopassword': opts.videopassword,
  680. 'ap_mso': opts.ap_mso,
  681. 'ap_username': opts.ap_username,
  682. 'ap_password': opts.ap_password,
  683. 'client_certificate': opts.client_certificate,
  684. 'client_certificate_key': opts.client_certificate_key,
  685. 'client_certificate_password': opts.client_certificate_password,
  686. 'quiet': opts.quiet,
  687. 'no_warnings': opts.no_warnings,
  688. 'forceurl': opts.geturl,
  689. 'forcetitle': opts.gettitle,
  690. 'forceid': opts.getid,
  691. 'forcethumbnail': opts.getthumbnail,
  692. 'forcedescription': opts.getdescription,
  693. 'forceduration': opts.getduration,
  694. 'forcefilename': opts.getfilename,
  695. 'forceformat': opts.getformat,
  696. 'forceprint': opts.forceprint,
  697. 'print_to_file': opts.print_to_file,
  698. 'forcejson': opts.dumpjson or opts.print_json,
  699. 'dump_single_json': opts.dump_single_json,
  700. 'force_write_download_archive': opts.force_write_download_archive,
  701. 'simulate': (print_only or any_getting or None) if opts.simulate is None else opts.simulate,
  702. 'skip_download': opts.skip_download,
  703. 'format': opts.format,
  704. 'allow_unplayable_formats': opts.allow_unplayable_formats,
  705. 'ignore_no_formats_error': opts.ignore_no_formats_error,
  706. 'format_sort': opts.format_sort,
  707. 'format_sort_force': opts.format_sort_force,
  708. 'allow_multiple_video_streams': opts.allow_multiple_video_streams,
  709. 'allow_multiple_audio_streams': opts.allow_multiple_audio_streams,
  710. 'check_formats': opts.check_formats,
  711. 'listformats': opts.listformats,
  712. 'listformats_table': opts.listformats_table,
  713. 'outtmpl': opts.outtmpl,
  714. 'outtmpl_na_placeholder': opts.outtmpl_na_placeholder,
  715. 'paths': opts.paths,
  716. 'autonumber_size': opts.autonumber_size,
  717. 'autonumber_start': opts.autonumber_start,
  718. 'restrictfilenames': opts.restrictfilenames,
  719. 'windowsfilenames': opts.windowsfilenames,
  720. 'ignoreerrors': opts.ignoreerrors,
  721. 'force_generic_extractor': opts.force_generic_extractor,
  722. 'allowed_extractors': opts.allowed_extractors or ['default'],
  723. 'ratelimit': opts.ratelimit,
  724. 'throttledratelimit': opts.throttledratelimit,
  725. 'overwrites': opts.overwrites,
  726. 'retries': opts.retries,
  727. 'file_access_retries': opts.file_access_retries,
  728. 'fragment_retries': opts.fragment_retries,
  729. 'extractor_retries': opts.extractor_retries,
  730. 'retry_sleep_functions': opts.retry_sleep,
  731. 'skip_unavailable_fragments': opts.skip_unavailable_fragments,
  732. 'keep_fragments': opts.keep_fragments,
  733. 'concurrent_fragment_downloads': opts.concurrent_fragment_downloads,
  734. 'buffersize': opts.buffersize,
  735. 'noresizebuffer': opts.noresizebuffer,
  736. 'http_chunk_size': opts.http_chunk_size,
  737. 'continuedl': opts.continue_dl,
  738. 'noprogress': opts.quiet if opts.noprogress is None else opts.noprogress,
  739. 'progress_with_newline': opts.progress_with_newline,
  740. 'progress_template': opts.progress_template,
  741. 'playliststart': opts.playliststart,
  742. 'playlistend': opts.playlistend,
  743. 'playlistreverse': opts.playlist_reverse,
  744. 'playlistrandom': opts.playlist_random,
  745. 'lazy_playlist': opts.lazy_playlist,
  746. 'noplaylist': opts.noplaylist,
  747. 'logtostderr': opts.outtmpl.get('default') == '-',
  748. 'consoletitle': opts.consoletitle,
  749. 'nopart': opts.nopart,
  750. 'updatetime': opts.updatetime,
  751. 'writedescription': opts.writedescription,
  752. 'writeannotations': opts.writeannotations,
  753. 'writeinfojson': opts.writeinfojson,
  754. 'allow_playlist_files': opts.allow_playlist_files,
  755. 'clean_infojson': opts.clean_infojson,
  756. 'getcomments': opts.getcomments,
  757. 'writethumbnail': opts.writethumbnail is True,
  758. 'write_all_thumbnails': opts.writethumbnail == 'all',
  759. 'writelink': opts.writelink,
  760. 'writeurllink': opts.writeurllink,
  761. 'writewebloclink': opts.writewebloclink,
  762. 'writedesktoplink': opts.writedesktoplink,
  763. 'writesubtitles': opts.writesubtitles,
  764. 'writeautomaticsub': opts.writeautomaticsub,
  765. 'allsubtitles': opts.allsubtitles,
  766. 'listsubtitles': opts.listsubtitles,
  767. 'subtitlesformat': opts.subtitlesformat,
  768. 'subtitleslangs': opts.subtitleslangs,
  769. 'matchtitle': decodeOption(opts.matchtitle),
  770. 'rejecttitle': decodeOption(opts.rejecttitle),
  771. 'max_downloads': opts.max_downloads,
  772. 'prefer_free_formats': opts.prefer_free_formats,
  773. 'trim_file_name': opts.trim_file_name,
  774. 'verbose': opts.verbose,
  775. 'dump_intermediate_pages': opts.dump_intermediate_pages,
  776. 'write_pages': opts.write_pages,
  777. 'load_pages': opts.load_pages,
  778. 'test': opts.test,
  779. 'keepvideo': opts.keepvideo,
  780. 'min_filesize': opts.min_filesize,
  781. 'max_filesize': opts.max_filesize,
  782. 'min_views': opts.min_views,
  783. 'max_views': opts.max_views,
  784. 'daterange': opts.date,
  785. 'cachedir': opts.cachedir,
  786. 'youtube_print_sig_code': opts.youtube_print_sig_code,
  787. 'age_limit': opts.age_limit,
  788. 'download_archive': opts.download_archive,
  789. 'break_on_existing': opts.break_on_existing,
  790. 'break_on_reject': opts.break_on_reject,
  791. 'break_per_url': opts.break_per_url,
  792. 'skip_playlist_after_errors': opts.skip_playlist_after_errors,
  793. 'cookiefile': opts.cookiefile,
  794. 'cookiesfrombrowser': opts.cookiesfrombrowser,
  795. 'legacyserverconnect': opts.legacy_server_connect,
  796. 'nocheckcertificate': opts.no_check_certificate,
  797. 'prefer_insecure': opts.prefer_insecure,
  798. 'enable_file_urls': opts.enable_file_urls,
  799. 'http_headers': opts.headers,
  800. 'proxy': opts.proxy,
  801. 'socket_timeout': opts.socket_timeout,
  802. 'bidi_workaround': opts.bidi_workaround,
  803. 'debug_printtraffic': opts.debug_printtraffic,
  804. 'prefer_ffmpeg': opts.prefer_ffmpeg,
  805. 'include_ads': opts.include_ads,
  806. 'default_search': opts.default_search,
  807. 'dynamic_mpd': opts.dynamic_mpd,
  808. 'extractor_args': opts.extractor_args,
  809. 'youtube_include_dash_manifest': opts.youtube_include_dash_manifest,
  810. 'youtube_include_hls_manifest': opts.youtube_include_hls_manifest,
  811. 'encoding': opts.encoding,
  812. 'extract_flat': opts.extract_flat,
  813. 'live_from_start': opts.live_from_start,
  814. 'wait_for_video': opts.wait_for_video,
  815. 'mark_watched': opts.mark_watched,
  816. 'merge_output_format': opts.merge_output_format,
  817. 'final_ext': final_ext,
  818. 'postprocessors': postprocessors,
  819. 'fixup': opts.fixup,
  820. 'source_address': opts.source_address,
  821. 'call_home': opts.call_home,
  822. 'sleep_interval_requests': opts.sleep_interval_requests,
  823. 'sleep_interval': opts.sleep_interval,
  824. 'max_sleep_interval': opts.max_sleep_interval,
  825. 'sleep_interval_subtitles': opts.sleep_interval_subtitles,
  826. 'external_downloader': opts.external_downloader,
  827. 'download_ranges': opts.download_ranges,
  828. 'force_keyframes_at_cuts': opts.force_keyframes_at_cuts,
  829. 'list_thumbnails': opts.list_thumbnails,
  830. 'playlist_items': opts.playlist_items,
  831. 'xattr_set_filesize': opts.xattr_set_filesize,
  832. 'match_filter': opts.match_filter,
  833. 'color': opts.color,
  834. 'ffmpeg_location': opts.ffmpeg_location,
  835. 'hls_prefer_native': opts.hls_prefer_native,
  836. 'hls_use_mpegts': opts.hls_use_mpegts,
  837. 'hls_split_discontinuity': opts.hls_split_discontinuity,
  838. 'external_downloader_args': opts.external_downloader_args,
  839. 'postprocessor_args': opts.postprocessor_args,
  840. 'cn_verification_proxy': opts.cn_verification_proxy,
  841. 'geo_verification_proxy': opts.geo_verification_proxy,
  842. 'geo_bypass': opts.geo_bypass,
  843. 'geo_bypass_country': opts.geo_bypass_country,
  844. 'geo_bypass_ip_block': opts.geo_bypass_ip_block,
  845. '_warnings': warnings,
  846. '_deprecation_warnings': deprecation_warnings,
  847. 'compat_opts': opts.compat_opts,
  848. })
  849. def _real_main(argv=None):
  850. setproctitle('yt-dlp')
  851. parser, opts, all_urls, ydl_opts = parse_options(argv)
  852. # Dump user agent
  853. if opts.dump_user_agent:
  854. ua = traverse_obj(opts.headers, 'User-Agent', casesense=False, default=std_headers['User-Agent'])
  855. write_string(f'{ua}\n', out=sys.stdout)
  856. return
  857. if print_extractor_information(opts, all_urls):
  858. return
  859. # We may need ffmpeg_location without having access to the YoutubeDL instance
  860. # See https://github.com/yt-dlp/yt-dlp/issues/2191
  861. if opts.ffmpeg_location:
  862. FFmpegPostProcessor._ffmpeg_location.set(opts.ffmpeg_location)
  863. with YoutubeDL(ydl_opts) as ydl:
  864. pre_process = opts.update_self or opts.rm_cachedir
  865. actual_use = all_urls or opts.load_info_filename
  866. if opts.rm_cachedir:
  867. ydl.cache.remove()
  868. try:
  869. updater = Updater(ydl, opts.update_self)
  870. if opts.update_self and updater.update() and actual_use:
  871. if updater.cmd:
  872. return updater.restart()
  873. # This code is reachable only for zip variant in py < 3.10
  874. # It makes sense to exit here, but the old behavior is to continue
  875. ydl.report_warning('Restart yt-dlp to use the updated version')
  876. # return 100, 'ERROR: The program must exit for the update to complete'
  877. except Exception:
  878. traceback.print_exc()
  879. ydl._download_retcode = 100
  880. if not actual_use:
  881. if pre_process:
  882. return ydl._download_retcode
  883. ydl.warn_if_short_id(sys.argv[1:] if argv is None else argv)
  884. parser.error(
  885. 'You must provide at least one URL.\n'
  886. 'Type yt-dlp --help to see a list of all options.')
  887. parser.destroy()
  888. try:
  889. if opts.load_info_filename is not None:
  890. if all_urls:
  891. ydl.report_warning('URLs are ignored due to --load-info-json')
  892. return ydl.download_with_info_file(expand_path(opts.load_info_filename))
  893. else:
  894. return ydl.download(all_urls)
  895. except DownloadCancelled:
  896. ydl.to_screen('Aborting remaining downloads')
  897. return 101
  898. def main(argv=None):
  899. global _IN_CLI
  900. _IN_CLI = True
  901. try:
  902. _exit(*variadic(_real_main(argv)))
  903. except DownloadError:
  904. _exit(1)
  905. except SameFileError as e:
  906. _exit(f'ERROR: {e}')
  907. except KeyboardInterrupt:
  908. _exit('\nERROR: Interrupted by user')
  909. except BrokenPipeError as e:
  910. # https://docs.python.org/3/library/signal.html#note-on-sigpipe
  911. devnull = os.open(os.devnull, os.O_WRONLY)
  912. os.dup2(devnull, sys.stdout.fileno())
  913. _exit(f'\nERROR: {e}')
  914. except optparse.OptParseError as e:
  915. _exit(2, f'\n{e}')
  916. from .extractor import gen_extractors, list_extractors
  917. __all__ = [
  918. 'main',
  919. 'YoutubeDL',
  920. 'parse_options',
  921. 'gen_extractors',
  922. 'list_extractors',
  923. ]