def parse_htpasswd(fn, stop_username=None):
    """
    Returns a dictionary of usernames and hashed password entries.  If
    stop_username is given, parsing will be finished as soon as that
    username is encountered.
    """
    f = open(fn, 'rb')
    try:
        entries = {}
        for line in f.readlines():
            line = line.strip()
            if not line or line.startswith('#'):
                continue
            if ':' not in line:
                raise ValueError('Bad line (no :): %r' % line)
            username, entry_password = line.split(':', 1)
            entries[username] = entry_password
            if username == stop_username:
                break
        return entries
    finally:
        f.close()
