Return a file descriptor from a file object. If
    given an integer will simply return that integer back.

def _fileobj_to_fd(fileobj):
    """ Return a file descriptor from a file object. If
    given an integer will simply return that integer back. """
    if isinstance(fileobj, _INTEGER_TYPES):
        fd = fileobj
    else:
        for _integer_type in _INTEGER_TYPES:
            try:
                fd = _integer_type(fileobj.fileno())
                break
            except (AttributeError, TypeError, ValueError):
                continue
        else:
            raise ValueError("Invalid file object: {0!r}".format(fileobj))
    if fd < 0:
        raise ValueError("Invalid file descriptor: {0}".format(fd))
    return fd