codes_filter_configs.py.in 2.37 KB
Newer Older
1 2
#!/usr/bin/python2.7

3 4 5 6 7 8
#
# Copyright (C) 2014 University of Chicago.
# See COPYRIGHT notice in top-level directory.
#
#

9
from sys import stdout
10
import os
11
import argparse
12 13 14 15 16 17 18 19 20 21 22 23 24
import imp

# internal testing: import directly
#import configurator as conf

# dynamically load from lib path
def import_from(fname):
    path,name = os.path.split(fname)
    name,ext  = os.path.splitext(name) 

    fmod, fname, data = imp.find_module(name, [path])
    return imp.load_module(name,fmod,fname,data)

25
conf = import_from("@bindir@/_configurator.py")
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50

def main():
    args = parse_args()

    # load and check the module
    mod = conf.import_from(args.substitute_py)
    conf.check_cfields(mod)

    # check that pairs are actually pairs
    tp = args.token_pairs
    if len(tp) % 2 != 0:
        raise ValueError("token pairs must come in twos")

    # intitialize the configuration object 
    cfg = conf.configurator(mod, [])

    # build a lookup structure for the pairs, converting to numbers if 
    # possible
    tdict = { }
    for i in range(0, len(tp), 2):
        v = conf.try_num(tp[i+1])
        if v == None:
            v = tp[i+1]
        tdict[tp[i]] = v

51 52 53 54 55
    # hack - if we are using an output prefix, append the "dot" here
    if args.output_prefix == None:
        args.output_prefix = ""
    else:
        args.output_prefix = args.output_prefix + '.'
56 57 58 59
    # filter out the files
    # (cfg iterator returns nothing, eval'd for side effects)
    for i,_ in enumerate(cfg):
        for k in tdict:
60
            if k not in cfg.replace_map or tdict[k] != cfg.replace_map[k]:
61 62
                break
        else:
63
            stdout.write(args.output_prefix + "{:05d}".format(i) + "\n")
64 65 66 67 68

def parse_args():
    parser = argparse.ArgumentParser(\
            description="emit configuration files to stdout matching given "
            "token values")
69 70
    parser.add_argument("-o", "--output_prefix", help="prefix of output config "
            "files (Default: print only the filtered indices)", type=str)
71 72 73 74 75 76 77 78 79 80
    parser.add_argument("substitute_py", 
            help="input python file given to codes_configurator.py - see "
            "codes_configurator.py for details")
    parser.add_argument("token_pairs", nargs='*',
            help="a list of whitespace-separated token, replace pairs to "
            "filter the set of generated configuration files by")
    return parser.parse_args()

if __name__ == "__main__":
    main()