yt-dlp: yt_dlp Python: `write_string` TypeError: string argument expected, got 'bytes'

DO NOT REMOVE OR SKIP THE ISSUE TEMPLATE

  • I understand that I will be blocked if I intentionally remove or skip any mandatory* field

Checklist

  • I’m reporting a bug unrelated to a specific site
  • I’ve verified that I have updated yt-dlp to nightly or master (update instructions)
  • I’ve checked that all provided URLs are playable in a browser with the same IP and same login details
  • I’ve checked that all URLs and arguments with special characters are properly quoted or escaped
  • I’ve searched known issues and the bugtracker for similar issues including closed ones. DO NOT post duplicates
  • I’ve read the guidelines for opening an issue

Provide a description that is worded well enough to be understood

Running latest yt_dlp library in Python3.12, suddenly getting this error. Never faced this issue before, and there has been no code changes. As you can see in the traceback, I am passing in a youtube link as a String list to ydl.download.

Provide verbose output that clearly demonstrates the problem

  • Run your yt-dlp command with -vU flag added (yt-dlp -vU <your command line>)
  • If using API, add 'verbose': True to YoutubeDL params instead
  • Copy the WHOLE output (starting with [debug] Command-line config) and insert it below

Complete Verbose Output

Traceback (most recent call last):
  File "/workspace/all_functions/getCaptionsPython.py", line 327, in run_ydl_get_captions
    ydl.download(['https://www.youtube.com/watch?v=KkCXLABwHP0'])
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/YoutubeDL.py", line 3583, in download
    self.__download_wrapper(self.extract_info)(
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/YoutubeDL.py", line 3558, in wrapper
    res = func(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/YoutubeDL.py", line 1595, in extract_info
    return self.__extract_info(url, self.get_info_extractor(key), download, extra_info, process)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/YoutubeDL.py", line 1606, in wrapper
    return func(self, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/YoutubeDL.py", line 1741, in __extract_info
    ie_result = ie.extract(url)
                ^^^^^^^^^^^^^^^
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/extractor/common.py", line 732, in extract
    self.to_screen('Extracting URL: %s' % (
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/extractor/common.py", line 1200, in to_screen
    self._downloader.to_screen(f'[{self.IE_NAME}] {msg}', *args, **kwargs)
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/YoutubeDL.py", line 924, in to_screen
    self._write_string(
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/YoutubeDL.py", line 905, in _write_string
    write_string(message, out=out, encoding=self.params.get('encoding'))
  File "/layers/google.python.pip/pip/lib/python3.12/site-packages/yt_dlp/utils/_utils.py", line 1441, in write_string
    buffer.write(s.encode(enc, 'ignore') if enc else s)
TypeError: string argument expected, got 'bytes'

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 17 (7 by maintainers)

Most upvoted comments

Great news, adding the custom logger and just calling the Firebase logger as such fixed the issue. Thank you for the support @Grub4K !

from firebase_functions import logger

class MyLogger:
    def debug(self, msg):
        # For compatibility with youtube-dl, both debug and info are passed into debug
        # You can distinguish them by the prefix '[debug] '
        if msg.startswith('[debug] '):
            logger.debug(msg)
        else:
            self.info(msg)

    def info(self, msg):
        logger.log(msg)

    def warning(self, msg):
        logger.warn(msg)

    def error(self, msg):
        logger.error(msg)

I ran into the same issue using Cloud Functions on GCP, @bktubestamp solution worked well here’s my snippet for general cloud functions

import yt_dlp
import logging 

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class MyLogger:
    def debug(self, msg):
        if msg.startswith('[debug] '):
            logger.debug(msg)
        else:
            self.info(msg)

    def info(self, msg):
        logger.info(msg)

    def warning(self, msg):
        logger.warning(msg)

    def error(self, msg):
        logger.error(msg)

def yt_dlp_download(url: str, ydl_opts: dict):
    """Download media using yt-dlp and save it to a local file."""
    try:
        ydl_opts['logger'] = MyLogger()
        with yt_dlp.YoutubeDL(ydl_opts) as ydl:
            ydl.download([url])
    except Exception as e:
        print(f"Error in yt_dlp_download: {str(e)}")
        raise

I have confirmed this happens in Firebase function, but not re-producible in my local machine.