From cadacd4e3edc0e201b0b713494e33264ccddc92b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9-Patrick=20Bubel?= Date: Thu, 30 Jun 2016 17:57:07 +0200 Subject: [PATCH] Output template now supports '0*d' zero padding --- test/test_utils.py | 12 ++++++++++++ youtube_dl/YoutubeDL.py | 3 ++- youtube_dl/utils.py | 20 ++++++++++++++++++++ 3 files changed, 34 insertions(+), 1 deletion(-) diff --git a/test/test_utils.py b/test/test_utils.py index ed61e4c27..d5ee0074f 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -33,6 +33,7 @@ from youtube_dl.utils import ( ExtractorError, find_xpath_attr, fix_xml_ampersands, + auto_str_to_int_fmt, InAdvancePagedList, intlist_to_bytes, is_html, @@ -985,5 +986,16 @@ The first line self.assertEqual(urshift(3, 1), 1) self.assertEqual(urshift(-3, 1), 2147483646) + def test_auto_str_to_int_fmt(self): + input = {"foo": "bar", + "number": 1234, + "s_number": "001234"} + + self.assertEqual(auto_str_to_int_fmt("%(foo)s", input), "bar") + self.assertEqual(auto_str_to_int_fmt("%(number)d", input), "1234") + self.assertEqual(auto_str_to_int_fmt("%(s_number)d", input), "1234") + self.assertEqual(auto_str_to_int_fmt("%(s_number)07d", input), "0001234") + self.assertEqual(auto_str_to_int_fmt("%(foo)s%(number)d-%(s_number)d", input), "bar1234-1234") + if __name__ == '__main__': unittest.main() diff --git a/youtube_dl/YoutubeDL.py b/youtube_dl/YoutubeDL.py index 5036289b0..f1bc55840 100755 --- a/youtube_dl/YoutubeDL.py +++ b/youtube_dl/YoutubeDL.py @@ -41,6 +41,7 @@ from .compat import ( from .utils import ( age_restricted, args_to_str, + auto_str_to_int_fmt, ContentTooShortError, date_from_str, DateRange, @@ -588,7 +589,7 @@ class YoutubeDL(object): outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL) tmpl = compat_expanduser(outtmpl) - filename = tmpl % template_dict + filename = auto_str_to_int_fmt(tmpl, template_dict) # Temporary fix for #4787 # 'Treat' all problem characters by passing filename through preferredencoding # to workaround encoding issues with subprocess on python2 @ Windows diff --git a/youtube_dl/utils.py b/youtube_dl/utils.py index a2cfb48a6..bd4e9d942 100644 --- a/youtube_dl/utils.py +++ b/youtube_dl/utils.py @@ -2903,3 +2903,23 @@ def parse_m3u8_attributes(attrib): def urshift(val, n): return val >> n if val >= 0 else (val + 0x100000000) >> n + + +def auto_str_to_int_fmt(fmt, input): + """ + String formatting similar to '%' formatting, but supporting strings in the input for the 'd' conversion type. + """ + + regex_split = "(%\(\w+\)[0-9]*d)" + regex_grouped = "%\((\w+)\)[0-9]*d" + result = [] + + for s in re.split(regex_split, fmt): + match = re.match(regex_grouped, s) + if match is None: + result.append(s) + else: + mapping_key = match.group(1) + result.append(s % { mapping_key: int(input[mapping_key]) }) + + return "".join(result) % input \ No newline at end of file