
import os

closerange = os.closerange


def _prepare_for_tests():

    def d_closerange(*a):
        print(a)

    def d_get_maximum_file_descriptors():
        return 999

    import sys
    module = sys.modules[close_all_open_files.__module__]
    module.closerange = d_closerange
    module.get_maximum_file_descriptors = d_get_maximum_file_descriptors


def close_all_open_files(exclude=None):
    r"""
        >>> _prepare_for_tests()
        >>> close_all_open_files(None)
        (3, 999)
        >>> close_all_open_files([1,2,3,4])
        (5, 999)
        >>> close_all_open_files([4, 7, 5, 8, 9, 77, 998])
        (3, 4)
        (6, 7)
        (10, 77)
        (78, 998)
    """
    min_fd = 3
    max_fd = get_maximum_file_descriptors()

    if not exclude:
        closerange(min_fd, max_fd)
        return

    for ex_fd in sorted(exclude):
        if ex_fd < min_fd:
            continue
        if ex_fd == min_fd:
            min_fd = ex_fd + 1
            continue
        closerange(min_fd, ex_fd)
        min_fd = ex_fd + 1

    if min_fd and min_fd < max_fd:
        closerange(min_fd, max_fd)
    
