Use `NamedTemporaryFile` for `--check-formats`

This commit is contained in:
pukkandan 2021-06-12 20:48:06 +05:30
parent 45db527fa6
commit 21cd8fae49
No known key found for this signature in database
GPG Key ID: 0F00D95A001F4698
1 changed files with 29 additions and 24 deletions

View File

@ -20,6 +20,7 @@ import re
import shutil import shutil
import subprocess import subprocess
import sys import sys
import tempfile
import time import time
import tokenize import tokenize
import traceback import traceback
@ -86,7 +87,6 @@ from .utils import (
preferredencoding, preferredencoding,
prepend_extension, prepend_extension,
process_communicate_or_kill, process_communicate_or_kill,
random_uuidv4,
register_socks_protocols, register_socks_protocols,
RejectedVideoReached, RejectedVideoReached,
render_table, render_table,
@ -817,6 +817,21 @@ class YoutubeDL(object):
'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.') 'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
return outtmpl_dict return outtmpl_dict
def get_output_path(self, dir_type='', filename=None):
paths = self.params.get('paths', {})
assert isinstance(paths, dict)
path = os.path.join(
expand_path(paths.get('home', '').strip()),
expand_path(paths.get(dir_type, '').strip()) if dir_type else '',
filename or '')
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through preferredencoding
# to workaround encoding issues with subprocess on python2 @ Windows
if sys.version_info < (3, 0) and sys.platform == 'win32':
path = encodeFilename(path, True).decode(preferredencoding())
return sanitize_path(path, force=self.params.get('windowsfilenames'))
@staticmethod @staticmethod
def validate_outtmpl(tmpl): def validate_outtmpl(tmpl):
''' @return None or Exception object ''' ''' @return None or Exception object '''
@ -994,12 +1009,11 @@ class YoutubeDL(object):
def prepare_filename(self, info_dict, dir_type='', warn=False): def prepare_filename(self, info_dict, dir_type='', warn=False):
"""Generate the output filename.""" """Generate the output filename."""
paths = self.params.get('paths', {})
assert isinstance(paths, dict)
filename = self._prepare_filename(info_dict, dir_type or 'default') filename = self._prepare_filename(info_dict, dir_type or 'default')
if warn and not self.__prepare_filename_warned: if warn and not self.__prepare_filename_warned:
if not paths: if not self.params.get('paths'):
pass pass
elif filename == '-': elif filename == '-':
self.report_warning('--paths is ignored when an outputting to stdout') self.report_warning('--paths is ignored when an outputting to stdout')
@ -1009,18 +1023,7 @@ class YoutubeDL(object):
if filename == '-' or not filename: if filename == '-' or not filename:
return filename return filename
homepath = expand_path(paths.get('home', '').strip()) return self.get_output_path(dir_type, filename)
assert isinstance(homepath, compat_str)
subdir = expand_path(paths.get(dir_type, '').strip()) if dir_type else ''
assert isinstance(subdir, compat_str)
path = os.path.join(homepath, subdir, filename)
# Temporary fix for #4787
# 'Treat' all problem characters by passing filename through preferredencoding
# to workaround encoding issues with subprocess on python2 @ Windows
if sys.version_info < (3, 0) and sys.platform == 'win32':
path = encodeFilename(path, True).decode(preferredencoding())
return sanitize_path(path, force=self.params.get('windowsfilenames'))
def _match_entry(self, info_dict, incomplete=False, silent=False): def _match_entry(self, info_dict, incomplete=False, silent=False):
""" Returns None if the file should be downloaded """ """ Returns None if the file should be downloaded """
@ -1742,18 +1745,20 @@ class YoutubeDL(object):
def _check_formats(formats): def _check_formats(formats):
for f in formats: for f in formats:
self.to_screen('[info] Testing format %s' % f['format_id']) self.to_screen('[info] Testing format %s' % f['format_id'])
paths = self.params.get('paths', {}) temp_file = tempfile.NamedTemporaryFile(
temp_file = os.path.join( suffix='.tmp', delete=False,
expand_path(paths.get('home', '').strip()), dir=self.get_output_path('temp') or None)
expand_path(paths.get('temp', '').strip()), temp_file.close()
'ytdl.%s.f%s.check-format' % (random_uuidv4(), f['format_id']))
try: try:
dl, _ = self.dl(temp_file, f, test=True) dl, _ = self.dl(temp_file.name, f, test=True)
except (ExtractorError, IOError, OSError, ValueError) + network_exceptions: except (ExtractorError, IOError, OSError, ValueError) + network_exceptions:
dl = False dl = False
finally: finally:
if os.path.exists(temp_file): if os.path.exists(temp_file.name):
os.remove(temp_file) try:
os.remove(temp_file.name)
except OSError:
self.report_warning('Unable to delete temporary file "%s"' % temp_file.name)
if dl: if dl:
yield f yield f
else: else: