It has been observed that using os.fdopen() below in multi-threaded scenarios is causing EBADF (thus OSError). There is probably a racen condition down in the stack or mkstemp() itself is not guaranteed against concurrent access. For now, just consume one more file descriptor and avoid the race completely.