yt-dlp/yt-dlp · error · OSError

Unlocking file failed: {ctypes.FormatError()!r}

Error message

Unlocking file failed: {ctypes.FormatError()!r}

What it means

Error "Unlocking file failed: {ctypes.FormatError()!r}" thrown in yt-dlp/yt-dlp.

Source

Thrown at yt_dlp/utils/_utils.py:1588

    def _lock_file(f, exclusive, block):
        overlapped = OVERLAPPED()
        overlapped.Offset = 0
        overlapped.OffsetHigh = 0
        overlapped.hEvent = 0
        f._lock_file_overlapped_p = ctypes.pointer(overlapped)

        if not LockFileEx(msvcrt.get_osfhandle(f.fileno()),
                          (0x2 if exclusive else 0x0) | (0x0 if block else 0x1),
                          0, whole_low, whole_high, f._lock_file_overlapped_p):
            # NB: No argument form of "ctypes.FormatError" does not work on PyPy
            raise BlockingIOError(f'Locking file failed: {ctypes.FormatError(ctypes.GetLastError())!r}')

    def _unlock_file(f):
        assert f._lock_file_overlapped_p
        handle = msvcrt.get_osfhandle(f.fileno())
        if not UnlockFileEx(handle, 0, whole_low, whole_high, f._lock_file_overlapped_p):
            raise OSError(f'Unlocking file failed: {ctypes.FormatError()!r}')

else:
    try:
        import fcntl

        def _lock_file(f, exclusive, block):
            flags = fcntl.LOCK_EX if exclusive else fcntl.LOCK_SH
            if not block:
                flags |= fcntl.LOCK_NB
            try:
                fcntl.flock(f, flags)
            except BlockingIOError:
                raise
            except OSError:  # AOSP does not have flock()
                fcntl.lockf(f, flags)

        def _unlock_file(f):
            with contextlib.suppress(OSError):

View on GitHub (pinned to 81ecd58b13)

Solutions

  1. The file handle was already closed or the lock region was invalid; this usually indicates a prior error, so check earlier log output.
  2. Retry the operation; if it persists, ensure no external tool modified or locked the file concurrently.

Example fix

Check the return value of UnlockFileEx: if not ctypes.windll.kernel32.UnlockFileEx(...): raise OSError(f'Unlocking file failed: {ctypes.FormatError()!r}')

When it happens

Trigger: Thrown at yt_dlp/utils/_utils.py:1588 when the library encounters an invalid state.

Common situations: See trigger scenarios.


AI-assisted analysis of yt-dlp/yt-dlp@81ecd58b13 (2026-08-22). Data as JSON: /api/errors/033e657c5741995f. Report an issue: GitHub.