Ejemplo n.º 1
0
def ShowSyntax(exit_code=0):
    """
    Print basic help information on using this module as a script

    :param int exit_code: Exit code.

    """
    print(sys.argv[0])
    print("Interpolate the observed points of a tropical cyclone temporally")
    print("for use in modelling a scenario event in TCRM")
    print("Example usage:")
    print("{0} -c <config file> -l <log file> -v".format(sys.argv[0]))
    print("")
    print("Options:")
    print("-h, --help:   prints this help message")
    print("-c, --config: configuration path (default value is {0})".format(
        flConfigFile()))
    print(
        "-l --logfile: path to log file to record actions (default value is {0})"
        .format(flConfigFile(".log")))
    print(
        "-v --verbose: True|False - print all logging messages to the screen")
    print("")
    print("Created by Craig Arthur, 2007-10-25 9:51:AM")
    print(__version__)
    sys.exit(exit_code)
Ejemplo n.º 2
0
def main(argv):
    """
    Main part of the program

    :param list argv: List of command line arguments.

    """
    gConfigFile = flConfigFile()
    #logFile = flConfigFile(".log")
    #verbose = False
    logger = logging.getLogger()

    try:
        opts, args = getopt.getopt(argv, "hc:l:v",
                                   ["help", "config=", "logfile=", "verbose"])
    except getopt.GetoptError:
        ShowSyntax(2)

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            ShowSyntax()
            sys.exit(2)
        elif opt in ("-c", "--config"):
            gConfigFile = arg
        elif opt in ("-l", "--logfile"):
            logFile = arg
        elif opt in ("-v", "--verbose"):
            verbose = True

    flStartLog(
        cnfGetIniValue(gConfigFile, 'Logging', 'LogFile',
                       flConfigFile('.log')),
        cnfGetIniValue(gConfigFile, 'Logging', 'LogLevel', 'INFO'),
        cnfGetIniValue(gConfigFile, 'Logging', 'Verbose', False))

    inputFile = cnfGetIniValue(gConfigFile, 'Input', 'File')
    logger.info("Processing {0}".format(inputFile))
    source = cnfGetIniValue(gConfigFile, 'Input', 'Source')
    delta = cnfGetIniValue(gConfigFile, 'Output', 'Delta', 0.1)

    nid, newtime, newdates, nLon, nLat, nthetaFm, \
        nvFm, npCentre, npEnv, nrMax = \
                    interpolateTrack(gConfigFile, inputFile, source, delta)
    #header = ''
    outputFile = cnfGetIniValue(gConfigFile, 'Output', 'File')
    logger.info("Saving interpolated data to {0}".format(outputFile))
    fh = open(outputFile, 'w')
    for i in xrange(len(newtime)):
        fh.write("%d,%5.1f,%s,%6.2f,%6.2f,%6.2f,%6.2f,%7.2f,%7.2f,%5.1f\n" %
                 (nid[i], newtime[i], newdates[i].strftime("%Y-%m-%d %H:%M"),
                  nLon[i], nLat[i], nthetaFm[i], nvFm[i], npCentre[i],
                  npEnv[i], nrMax[i]))
    fh.close()
    logger.info("Completed {0}".format(sys.argv[0]))
Ejemplo n.º 3
0
def cnfCacheIniFile(configFile=None):
    """
    A wrapper to the ConfigParser module which caches a dictionary of
    dictionaries. Each dictionary in the parent dictionary is named
    after sections in the configuration file. Keys in the
    sub-directories are named by the options in each section.

    Input: configuration file name (optional, defaults to output from
           flConfigFile())
    Output: configuration dictionary
    Example: CONFIG_DICT = cnfCacheIniFile(configFile)
    """
    if configFile:
        try:
            fh = open(configFile)
        except IOError:
            LOG.info("Cannot open %s", configFile)
            return CONFIG_DICT
    elif len(sys.argv) > 1:
        try:
            fh = open(sys.argv[1])
        except IOError:
            LOG.info("No configuration file given at command line")
    else:
        try:
            fh = open(flConfigFile(level=len(inspect.stack())))
            LOG.info("Opening default config file %s",
                     flConfigFile(level=len(inspect.stack())))
        except IOError:
            LOG.info("Cannot open default config file %s",
                     flConfigFile(level=len(inspect.stack())))
            return CONFIG_DICT

    cp = ConfigParser.ConfigParser()
    cp.optionxform = str
    cp.readfp(fh)
    for sec in cp.sections():
        name = sec
        if name not in CONFIG_DICT:
            CONFIG_DICT[name] = {}
        for opt in cp.options(sec):
            try:
                CONFIG_DICT[name][opt] = cp.getint(sec, opt)
            except ValueError:
                try:
                    CONFIG_DICT[name][opt] = cp.getfloat(sec, opt)
                except ValueError:
                    try:
                        CONFIG_DICT[name][opt] = cp.getboolean(sec, opt)
                    except ValueError:
                        CONFIG_DICT[name][opt] = cp.get(sec, opt)
    fh.close()
    return CONFIG_DICT
Ejemplo n.º 4
0
def cnfGetIniList(configFile, section, first=1, last=None):
    """
    Get a list of values for integer options in a configuration file.
    Input: ini file name, section, first value (optional, default 1)
    Output: list, or number of values in scalar context
    Example: out = cnfGetIniList(fileName, section, first=1, last=None)

    First value defaults to 1. Last is the last value which will be
    tried.  Allows gaps in the sequence, but there should not be
    duplicate values (we can't define which would be retrieved!).
    """
    if configFile is None:
        fh = open(flConfigFile())
    else:
        fh = open(configFile)
    cp = ConfigParser.ConfigParser()
    cp.optionxform = str
    cp.readfp(fh)
    values = []
    try:
        options = cp.options(section)
    except ConfigParser.NoSectionError:
        LOG.exception("No section named %s in configuration file %s",
                      section, configFile)
        fh.close()
        raise

    options = [int(o) for o in options]
    options.sort()
    for opt in options:
        if last:
            if (int(opt) >= first) and (int(opt) <= last):
                try:
                    values.append(cp.getint(section, str(opt)))
                except ValueError:
                    try:
                        values.append(cp.getfloat(section, str(opt)))
                    except ValueError:
                        try:
                            values.append(cp.getboolean(section, str(opt)))
                        except ValueError:
                            values.append(cp.get(section, str(opt)))
        else:
            if int(opt) >= first:
                try:
                    values.append(cp.getint(section, str(opt)))
                except ValueError:
                    try:
                        values.append(cp.getfloat(section, str(opt)))
                    except ValueError:
                        try:
                            values.append(cp.getboolean(section, str(opt)))
                        except ValueError:
                            values.append(cp.get(section, str(opt)))
    fh.close()
    return values
Ejemplo n.º 5
0
def cnfGetIniFileValue(configFile, section, option, default=None):
    """
    Get a value directly from the configuration file, rather than
    using a cached value.  This shouldn't be used in anger, as it may
    produce adverse effects if you make changes to the config file
    while a program is running. Optionally takes a default value to
    return if the option is not in the configuration file.

    Input: configuration file name, section name, option name, default
    value.
    Output: value directly from the configuration file.
    Example: value = cnfGetIniFileValue(configFile, section, option,
                                        default)
    """
    if configFile is None:
        fh = open(flConfigFile())
    else:
        fh = open(configFile)
    cp = ConfigParser.ConfigParser()
    cp.optionxform = str
    cp.readfp(fh)
    try:
        sections = cp.sections()
    except ConfigParser.NoSectionError:
        LOG.exception("No section named %s in configuration file %s",
                      section, configFile)
        fh.close()
        raise

    if section in sections:
        options = cp.options(section)
        if option in options:
            try:
                value = cp.getint(section, option)
            except ValueError:
                try:
                    value = cp.getfloat(section, option)
                except ValueError:
                    try:
                        value = cp.getboolean(section, option)
                    except ValueError:
                        value = cp.get(section, option)
        else:
            value = default
    else:
        value = default
    fh.close()
    return value
Ejemplo n.º 6
0
def cnfGetUnorderedList(configFile, section):
    """
    Get a list of unordered values in the given section.

    Input: ini file name, section
    Output: list, or number of values in scalar context
    Example: out = cnfGetUnorderdedList( filename, section )

    This function requires a different approach to reading
    the configuration file, as ConfigParser in Python versions
    prior to 2.7 cannot handle options with no value. The workaround
    reads the configuration file and constructs a dict similar
    to CONFIG_DICT used elsewhere in this module.
    Lists of unordered values are included in the dict with the
    key and subkey equal to the section name.
    i.e. cfgDict[ section ][ section ] = [list]


    """
    sect = None
    sect_list = []
    cfgDict = {}
    if configFile is None:
        configFile = flConfigFile()
    try:
        fh = open(configFile)
    except IOError:
        LOG.warn("Cannot open %s", configFile)
    else:
        for line in fh:
            line = line.lstrip().rstrip('\n')
            cm = re.match('^;', line)
            if cm:
                # Ignore lines that begin with a comment character
                continue
            sm = re.match(r'^\[(\w*)\]', line)
            am = re.match(r'^([^=]+)=(.+)', line)
            if sm:
                new_sect = sm.group(1)
                if sect:
                    key = sect
                    subkey = key
                    cfgDict[key][subkey] = sect_list
                sect = new_sect
                sect_list = []

            elif am:
                # Attribute/value pair
                att = am.group(1)
                val = am.group(2)
                att = att.rstrip()
                val = val.rstrip().lstrip()
                if cfgDict.has_key(sect):
                    cfgDict[sect][att] = val
                else:
                    cfgDict[sect] = {}
                    cfgDict[sect][att] = val
            elif len(line):
                sect_list.append(line)

        fh.close()

    return cfgDict[section][section]