def main(argv=None):

    if argv is None:
        argv = sys.argv

    # setup command line parser
    parser = E.OptionParser(version="%prog version: $Id$",
                            usage=globals()["__doc__"])

    parser.add_option("-g", "--glob", dest="glob", type="string",
                      help="glob of emails to scan")

    parser.add_option("-m", "--multiple-projects", dest="multiple",
                      type="string",
                      action="append",
                      help="project folder with multiple projects")

    parser.set_defaults(
        glob="/ifs/home/andreas/mail/Local Folders/Projects.sbd/*",
        regex="CGAT-PROJECT-(\d+)@JISCMAIL.AC.UK",
        max_emails=100,
        multiple=[],
        )

    # add common options (-h/--help, ...) and parse command line
    (options, args) = E.Start(parser, argv=argv)

    if options.multiple:
        options.multiple = dict([x.split("=") for x in options.multiple])

    filenames = glob.glob(options.glob)

    rx_project = re.compile(options.regex, re.I)
    max_emails = options.max_emails
    outfile = options.stdout
    outfile.write("project_id\treceived\tfilename\tscanned\n")

    for filename in filenames:
        if filename.endswith(".msf"):
            continue

        E.debug("working on %s" % filename)

        basename = os.path.basename(filename)
        if basename in options.multiple:
            expected = set([x.strip() for x in
                            options.multiple[basename].split(":")])
        else:
            expected = set([])

        found = {}

        received = None
        project_id = None

        for n, message in enumerate(
                generate_message(
                    reverse_readline(filename))):

            for line in message:
                if line.startswith("From - "):
                    received = line[7:]
                    continue
                x = rx_project.search(line)
                if x is not None:
                    project_id = x.groups()[0]
                    break
                if line.startswith("MIME-Version"):
                    break

            if project_id is not None:
                found[project_id] = received

            if expected is not None:
                if project_id in expected:
                    expected.remove(project_id)

            if n > max_emails:
                break

            if found and len(expected) == 0:
                break

        for project_id, received in found.items():
            line = "\t".join(map(str, (
                project_id,
                received,
                filename,
                n)))
            # remove ^M characters in fields
            line = re.sub("\r", "", line)
            outfile.write(line + "\n")

    # write footer and output benchmark information.
    E.Stop()
script main.
dataset/ETHPy150Open CGATOxford/cgat/scripts/cgat_scan_email.py/main