def random_useragent(filename=True):
    """Returns a User-Agent string randomly from file.

    :arg string filename: (Optional) Path to the file from which a random
        useragent is generated. By default it's ``True``, a file shipped
        with this module will be used.
    :returns: An user-agent string.
    """
    import random

    default_ua = 'urlfetch/%s' % __version__

    if isinstance(filename, basestring):
        filenames = [filename]
    else:
        filenames = []

    if filename and UAFILE:
        filenames.append(UAFILE)

    for filename in filenames:
        try:
            st = os.stat(filename)
            if stat.S_ISREG(st.st_mode) and os.access(filename, os.R_OK):
                break
        except:
            pass
    else:
        return default_ua

    with open(filename, 'rb') as f:
        filesize = st.st_size
        pos = 0
        r = random.Random()

        # try getting a valid line for no more than 3 times
        for i in range(3):

            pos += r.randint(0, filesize)
            pos %= filesize
            f.seek(pos)

            # in case we are in middle of a line
            f.readline()

            line = f.readline()
            if not line:
                if f.tell() == filesize:
                    # end of file
                    f.seek(0)
                    line = f.readline()

            line = line.strip()
            if line and line[0] != '#':
                return line

    return default_ua
Returns a User-Agent string randomly from file.

    :arg string filename: (Optional) Path to the file from which a random
        useragent is generated. By default it's ``True``, a file shipped
        with this module will be used.
    :returns: An user-agent string.