class ConfigReader(object): """ 为傲世堂的游戏项目配置文件定制的配置读取类。 陈超写的arg.gameOption耦合性太强,只能在bible内使用。 但是配置文件的结构设计的很合理。 此类就是根据原来的结构设计重新写的解耦并且适用性更广的类。 Example:: conf = ConfigReader(game, region) ip = conf.get("mobile_www_ip") if conf.has_option("mobile_www_port") port = conf.getint("mobile_www_port") """ def __init__(self, game, section, conf_dir='/app/opbin/work/bible/conf'): self.game = game self.section = section self.conf_file = '{}/{}.conf'.format(conf_dir.rstrip('/'), self.game) self.config = ConfigParser() self.config.read(self.conf_file) self.has_section = self.config.has_section(self.section) def has_option(self, option): return self._has_option(self.section, option) or self._has_option('common', option) def _has_option(self, section, option): return self.config.has_option(section, option) def get(self, option, raw=0, var=None): if self._has_option(self.section, option): return self.config.get(self.section, option, raw, var) elif self._has_option('common', option): return self.config.get('common', option, raw, var) else: raise Exception("Can't find option: {} in {}".format(option, self.conf_file)) def getint(self, option): if self._has_option(self.section, option): return self.config.getint(self.section, option) elif self._has_option('common', option): return self.config.getint('common', option) else: raise Exception("Can't find option: {} in {}".format(option, self.conf_file)) def getfloat(self, option): if self._has_option(self.section, option): return self.config.getfloat(self.section, option) elif self._has_option('common', option): return self.config.getfloat('common', option) else: raise Exception("Can't find option: {} in {}".format(option, self.conf_file)) def getboolean(self, option): if self._has_option(self.section, option): return self.config.getboolean(self.section, option) elif self._has_option('common', option): return self.config.getboolean('common', option) else: raise Exception("Can't find option: {} in {}".format(option, self.conf_file))
def read_metadata(filename): if filename.endswith('bz2'): fname = os.path.splitext(filename)[0] else: fname = filename if os.path.splitext(fname)[1] == '.cbf': try: import pycbf except ImportError: raise NeXusError('Reading CBF files requires the pycbf module') cbf = pycbf.cbf_handle_struct() cbf.read_file(fname, pycbf.MSG_DIGEST) cbf.select_datablock(0) cbf.select_category(0) cbf.select_column(1) meta_text = cbf.get_value().splitlines() date_string = meta_text[2][2:] time_stamp = epoch(date_string) exposure = float(meta_text[5].split()[2]) summed_exposures = 1 return time_stamp, exposure, summed_exposures elif os.path.exists(fname+'.metadata'): parser = ConfigParser() parser.read(fname+'.metadata') return (parser.getfloat('metadata', 'timeStamp'), parser.getfloat('metadata', 'exposureTime'), parser.getint('metadata', 'summedExposures')) else: return time.time(), 1.0, 1
def read_config(filename): """Read the config file *filename* and replace the values in global variables. """ cfg = ConfigParser() cfg.read(filename) station = cfg.get("default", "station") satellites = cfg.get("default", "satellites").split(",") forward = cfg.getint("default", "forward") start = cfg.getfloat("default", "start") station_name = cfg.get(station, "name") station_lon = cfg.getfloat(station, "longitude") station_lat = cfg.getfloat(station, "latitude") station_alt = cfg.getfloat(station, "altitude") sat_scores = {} for sat in satellites: sat_scores[sat] = (cfg.getfloat(sat, "night"), cfg.getfloat(sat, "day")) area = utils.parse_area_file(cfg.get(station, "area_file"), cfg.get(station, "area"))[0] return ((station_lon, station_lat, station_alt), sat_scores, station_name, area, forward, start)
def __init__(self): config = ConfigParser() defaults = getDefaults() config.read(defaults) # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get("sachdrs", "twhdrs").split() self.hdrsel = config.get("sachdrs", "hdrsel") self.qfactors = config.get("sachdrs", "qfactors").split() self.qheaders = config.get("sachdrs", "qheaders").split() self.qweights = [float(val) for val in config.get("sachdrs", "qweights").split()] # SAC plots self.figsize = [float(val) for val in config.get("sacplot", "figsize").split()] self.rectseis = [float(val) for val in config.get("sacplot", "rectseis").split()] self.colorwave = config.get("sacplot", "colorwave") self.colorwavedel = config.get("sacplot", "colorwavedel") self.colortwfill = config.get("sacplot", "colortwfill") self.colortwsele = config.get("sacplot", "colortwsele") self.alphatwfill = config.getfloat("sacplot", "alphatwfill") self.alphatwsele = config.getfloat("sacplot", "alphatwsele") self.npick = config.getint("sacplot", "npick") self.pickcolors = config.get("sacplot", "pickcolors") self.pickstyles = config.get("sacplot", "pickstyles").split() self.minspan = config.getint("sacplot", "minspan") self.srate = config.getfloat("sacplot", "srate") self.tapertype = config.get("signal", "tapertype") self.taperwidth = config.getfloat("signal", "taperwidth") self.thresholds = [float(val) for val in config.get("sacplot", "thresholds").split()] self.colorthresholds = config.get("sacplot", "colorthresholds").split()
def __init__(self): config = ConfigParser() defaults = getDefaults() config.read(defaults) # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get('sachdrs', 'twhdrs').split() self.hdrsel = config.get('sachdrs', 'hdrsel') self.qfactors = config.get('sachdrs', 'qfactors').split() self.qheaders = config.get('sachdrs', 'qheaders').split() self.qweights = [ float(val) for val in config.get('sachdrs', 'qweights').split() ] # SAC plots self.figsize = [ float(val) for val in config.get('sacplot', 'figsize').split() ] self.rectseis = [ float(val) for val in config.get('sacplot', 'rectseis').split() ] self.colorwave = config.get('sacplot', 'colorwave') self.colorwavedel = config.get('sacplot', 'colorwavedel') self.colortwfill = config.get('sacplot', 'colortwfill') self.colortwsele = config.get('sacplot', 'colortwsele') self.alphatwfill = config.getfloat('sacplot', 'alphatwfill') self.alphatwsele = config.getfloat('sacplot', 'alphatwsele') self.npick = config.getint('sacplot', 'npick') self.pickcolors = config.get('sacplot', 'pickcolors') self.pickstyles = config.get('sacplot', 'pickstyles').split() self.minspan = config.getint('sacplot', 'minspan') self.srate = config.getfloat('sacplot', 'srate') self.tapertype = config.get('signal', 'tapertype') self.taperwidth = config.getfloat('signal', 'taperwidth')
def setUp(self): rid = '60754-10' config = ConfigParser() p = '/Users/ross/Sandbox/pychron_validation_data.cfg' config.read(p) signals = map(lambda x: map(float, x.split(',')), [config.get('Signals-{}'.format(rid), k) for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']]) blanks = map(lambda x: map(float, x.split(',')), [config.get('Blanks-{}'.format(rid), k) for k in ['ar40', 'ar39', 'ar38', 'ar37', 'ar36']]) irradinfo = map(lambda x: map(float, x.split(',')), [config.get('irrad-{}'.format(rid), k) for k in ['k4039', 'k3839', 'ca3937', 'ca3837', 'ca3637', 'cl3638']]) j = config.get('irrad-{}'.format(rid), 'j') j = map(lambda x: float(x), j.split(',')) baselines = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)] backgrounds = [(0, 0), (0, 0), (0, 0), (0, 0), (0, 0)] ar37df = config.getfloat('irrad-{}'.format(rid), 'ar37df') t = math.log(ar37df) / (constants.lambda_37.nominal_value * 365.25) irradinfo.append(t) # load results r = 'results-{}'.format(rid) self.age = config.getfloat(r, 'age') self.rad4039 = config.getfloat(r, 'rad4039') self.ca37k39 = config.getfloat(r, 'ca37k39') self.age_dict = calculate_arar_age(signals, baselines, blanks, backgrounds, j, irradinfo, )
def __init__(self): defaults = getDefaults() config = ConfigParser() config.read(defaults) self.tapertype = config.get("signal", "tapertype") self.taperwidth = config.getfloat("signal", "taperwidth") self.maxiter = config.getint("iccs", "maxiter") self.convepsi = config.getfloat("iccs", "convepsi") self.convtype = config.get("iccs", "convtype") self.stackwgt = config.get("iccs", "stackwgt") self.srate = config.getfloat("iccs", "srate") self.fstack = config.get("iccs", "fstack") # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get("sachdrs", "twhdrs").split() self.hdrsel = config.get("sachdrs", "hdrsel") self.qfactors = config.get("sachdrs", "qfactors").split() self.qheaders = config.get("sachdrs", "qheaders").split() self.qweights = [float(val) for val in config.get("sachdrs", "qweights").split()] # SAC headers for ICCS time picks self.ichdrs = config.get("sachdrs", "ichdrs").split() # Choose a xcorr module and function self.shift = config.getint("iccs", "shift") modu = config.get("iccs", "xcorr_modu") func = config.get("iccs", "xcorr_func") cmd = "from %s import %s; xcorr=%s" % (modu, func, func) exec cmd self.xcorr = xcorr self.xcorr_modu = modu self.xcorr_func = func
def __init__(self): defaults = getDefaults() config = ConfigParser() config.read(defaults) self.tapertype = config.get("signal", "tapertype") self.taperwidth = config.getfloat("signal", "taperwidth") self.lsqr = config.get("mccc", "lsqr") self.ofilename = config.get("mccc", "ofilename") self.tapertype = config.get("signal", "tapertype") self.taperwidth = config.getfloat("signal", "taperwidth") self.exwt = config.getfloat("mccc", "extraweight") self.srate = config.getfloat("mccc", "srate") self.rcfile = config.get("mccc", "rcfile") self.evlist = config.get("mccc", "evlist") self.fstack = config.get("iccs", "fstack") # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get("sachdrs", "twhdrs").split() self.hdrsel = config.get("sachdrs", "hdrsel") # SAC headers for MCCC time picks self.ipick, self.wpick = config.get("sachdrs", "mchdrs").split() # Choose a xcorr module and function self.shift = config.getint("mccc", "shift") modu = config.get("mccc", "xcorr_modu") func = config.get("mccc", "xcorr_func") cmd = "from %s import %s; xcorr=%s" % (modu, func, func) exec cmd self.xcorr = xcorr self.xcorr_modu = modu self.xcorr_func = func
def readIni(nb): global K, N, cut, gui, distrWE, distrNS, vehphWEA, vehphNSA, maxSumFlow, tlType, intergreenLength, GSum global phaseMinWE, phaseMaxWE, phaseMinNS, phaseMaxNS, maxGap, detPos filename = 'input' + str(nb).zfill(2) + '.ini' ini = ConfigParser() ini.read(filename) K = ini.getint("general", "K") N = ini.getint("general", "N") cut = ini.getboolean("general", "cut") gui = ini.getboolean("general", "gui") distrWE = ini.get("demand", "distrWE") distrNS = ini.get("demand", "distrNS") vehphWEA = eval(ini.get("demand", "vehphWEA")) vehphNSA = eval(ini.get("demand", "vehphNSA")) maxSumFlow = ini.getint("demand", "maxSumFlow") tlType = ini.get("TL", "tlType") intergreenLength = ini.getint("TL", "intergreenLength") GSum = ini.getfloat("TL", "GSum") [phaseMinWE, phaseMaxWE] = eval(ini.get("TL", "phaseMinMaxWE")) [phaseMinNS, phaseMaxNS] = eval(ini.get("TL", "phaseMinMaxNS")) maxGap = ini.getfloat("TL", "maxGap") detPos = ini.getfloat("TL", "detPos") return filename
def compileBlock(configFile, binFile): config = ConfigParser() config.read(configFile) block = (configVersion, ) block += (config.getint("radio", "channel"),) block += (speeds.index(config.get("radio", "speed").upper()),) block += (config.getfloat("calib", "pitchTrim"),) block += (config.getfloat("calib", "rollTrim"),) bin = struct.pack(structFormat, *block) #Adding some magic: bin = "0xBC" + bin bin += struct.pack("B", 256-checksum256(bin)) #print("Config block checksum: %02x" % bin[len(bin)-1]) bfile = open(binFile, "w") bfile.write(bin) bfile.close() print "Config block compiled successfully to", binFile
def read_header(folder, n_part, input_): global config config = ConfigParser() config.read(input_) h_data = [] for j in n_part: # n_part h_data.append(int(j)) for j in config.get('header', 'mass_array').split(','): h_data.append(float(j)) h_data.append(config.getfloat('header', 'time')) h_data.append(config.getfloat('header', 'redshift')) h_data.append(config.getint('header', 'flag_sfr')) h_data.append(config.getint('header', 'flag_feedback')) for j in n_part: # n_part_total, assuming equal to n_part h_data.append(int(j)) h_data.append(config.getint('header', 'flag_cooling')) h_data.append(config.getint('header', 'num_files')) h_data.append(config.getfloat('header', 'boxsize')) h_data.append(config.getfloat('header', 'omega0')) h_data.append(config.getfloat('header', 'omega_lambda')) h_data.append(config.getfloat('header', 'hubble_param')) h_data.append(config.getint('header', 'flag_age')) h_data.append(config.getint('header', 'flag_metals')) # blank, present in the header for i in np.arange(88): h_data.append('\0') s = struct.Struct('iiiiii dddddd d d i i iiiiii i i dddd ii cccc\ cccccccccccccccccccccccccccccccccccccccccccccccccc\ cccccccccccccccccccccccccccccccccc') packed_data = s.pack(*h_data) # Need raw h_data as well - D. Rennehan return packed_data, h_data
def get_ic_factor(self, det): # storing ic_factor in preferences causing issues # ic_factor stored in detectors.cfg p = os.path.join(paths.spectrometer_dir, 'detectors.cfg') # factors=None ic = 1, 1e-20 if os.path.isfile(p): c = ConfigParser() c.read(p) det = det.lower() for si in c.sections(): if si.lower() == det: v, e = 1, 1e-20 if c.has_option(si, 'ic_factor'): v = c.getfloat(si, 'ic_factor') if c.has_option(si, 'ic_factor_err'): e = c.getfloat(si, 'ic_factor_err') ic = v, e break else: self.debug('no detector file {}. cannot retrieve ic_factor'.format(p)) r = ufloat(*ic) return r
def __init__(self): defaults = getDefaults() config = ConfigParser() config.read(defaults) self.tapertype = config.get('signal', 'tapertype') self.taperwidth = config.getfloat('signal', 'taperwidth') self.lsqr = config.get('mccc', 'lsqr') self.ofilename = config.get('mccc', 'ofilename') self.tapertype = config.get('signal', 'tapertype') self.taperwidth = config.getfloat('signal', 'taperwidth') self.exwt = config.getfloat('mccc', 'extraweight') self.srate = config.getfloat('mccc', 'srate') self.rcfile = config.get('mccc', 'rcfile') self.evlist = config.get('mccc', 'evlist') self.fstack = config.get('iccs', 'fstack') # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get('sachdrs', 'twhdrs').split() self.hdrsel = config.get('sachdrs', 'hdrsel') # SAC headers for MCCC time picks self.ipick, self.wpick = config.get('sachdrs', 'mchdrs').split() # Choose a xcorr module and function self.shift = config.getint('mccc', 'shift') modu = config.get('mccc', 'xcorr_modu') func = config.get('mccc', 'xcorr_func') cmd = 'from %s import %s; xcorr=%s' % (modu, func, func) exec cmd self.xcorr = xcorr self.xcorr_modu = modu self.xcorr_func = func
def __init__(self): defaults = getDefaults() config = ConfigParser() config.read(defaults) self.tapertype = config.get('signal', 'tapertype') self.taperwidth = config.getfloat('signal', 'taperwidth') self.maxiter = config.getint('iccs', 'maxiter') self.convepsi = config.getfloat('iccs', 'convepsi') self.convtype = config.get('iccs', 'convtype') self.stackwgt = config.get('iccs', 'stackwgt') self.srate = config.getfloat('iccs', 'srate') self.fstack = config.get('iccs', 'fstack') # SAC headers for time window, trace selection, and quality factors self.twhdrs = config.get('sachdrs', 'twhdrs').split() self.hdrsel = config.get('sachdrs', 'hdrsel') self.qfactors = config.get('sachdrs', 'qfactors').split() self.qheaders = config.get('sachdrs', 'qheaders').split() self.qweights = [ float(val) for val in config.get('sachdrs', 'qweights').split() ] # SAC headers for ICCS time picks self.ichdrs = config.get('sachdrs', 'ichdrs').split() # Choose a xcorr module and function self.shift = config.getint('iccs', 'shift') modu = config.get('iccs', 'xcorr_modu') func = config.get('iccs', 'xcorr_func') cmd = 'from %s import %s; xcorr=%s' % (modu, func, func) exec cmd self.xcorr = xcorr self.xcorr_modu = modu self.xcorr_func = func
def test01(): from ConfigParser import ConfigParser CONFIGFILE='config.txt' config=ConfigParser() config.read(CONFIGFILE) print config.get('messages','greeting') radius=input(config.get('messages','question')+' ') print config.get('messages','result_message') print config.getfloat('numbers','pi')*radius**2
def load_glbv(): """load global variables from .xls""" glbv = {} glbv["path"] = "" glbv["config_file"] = "" if platform.system() == "Windows": glbv["path"] = "D:\Experiment\prefetching-simulation" glbv["config_file"] = glbv["path"]+"\project\glbv.conf" elif platform.system() == "Linux": glbv["path"] = "/home/pzy/test" glbv["config_file"] = glbv["path"]+"/glbv.conf" cf = ConfigParser() cf.read(glbv["config_file"]) glbv["tl"] = cf.getint("glbv", "tl") glbv["tn"] = cf.getint("glbv", "tn") glbv["t"] = cf.getint("glbv", "t") glbv["f"] = cf.getint("glbv", "f") glbv["n"] = cf.getint("glbv", "n") glbv["b"] = cf.getint("glbv", "b") glbv["ot"] = cf.getint("glbv", "ot") glbv["maxs"] = cf.getint("glbv", "maxs") glbv["mins"] = cf.getint("glbv", "mins") glbv["recall"] = cf.getfloat("glbv", "recall") glbv["precision"] = cf.getfloat("glbv", "precision") glbv["source"] = cf.get("glbv", "source") glbv["solver"] = cf.get("glbv", "solver") glbv["dis"] = cf.get("glbv", "dis") glbv["wrt"] = cf.get("glbv", "wrt") glbv["draw"] = cf.get("glbv", "draw") glbv["data1"] = cf.get("glbv", "data1") glbv["result1"] = cf.get("glbv", "result1") glbv["sheet_index"] = cf.getint("glbv", "sheet_index") glbv["time_col"] = cf.getint("glbv", "time_col") glbv["size_col"] = cf.getint("glbv", "size_col") glbv["start_row"] = cf.getint("glbv", "start_row") glbv["end_row"] = cf.getint("glbv", "end_row") glbv["t"] = glbv["tn"]*glbv["tl"] glbv["n"] = glbv["t"]/glbv["f"] if platform.system() == "Windows": glbv["data_file"] = glbv["path"]+"\\project\\"+glbv["data1"] glbv["result_file"] = glbv["path"]+"\\project\\"+glbv["result1"] elif platform.system() == "Linux": glbv["data_file"] = glbv["path"]+"/"+glbv["data1"] glbv["result_file"] = glbv["path"]+"/"+glbv["result1"] return glbv
def __init__(self, config_file="body_model.conf", section="BodyModel"): c = ConfigParser() if not path.exists(config_file): print 'Config file %s not found!'%config_file raise IOError c.read(config_file) self.legs = [LegModel() for i in range(NUM_LEGS)] # Leg Offsets self.LEG0_OFFSET_X = c.getfloat(section, "leg0_offset_x") self.LEG0_OFFSET_Y = c.getfloat(section, "leg0_offset_y") self.LEG0_THETA = c.getfloat(section, "leg0_theta") self.LEG1_OFFSET_X = c.getfloat(section, "leg1_offset_x") self.LEG1_OFFSET_Y = c.getfloat(section, "leg1_offset_y") self.CHASSIS_BOTTOM_Z = c.getfloat(section, "chassis_bottom_z")
def parseConfigurationFile(self, configFile): """ Parse the configuration file to get base model parameters """ # Initialize defaults defaultParams = {} # CUDA kernels are defined externally in a .cu file defaultParams["cu_dir"] = os.path.join("pyhawkes", "cuda", "cpp") defaultParams["cu_file"] = "process_id_kernels.cu" defaultParams["thin"] = 1 defaultParams["sigma"] = 0.001 defaultParams["kappa"] = 5 defaultParams["nu"] = 4 defaultParams["mu"] = "None" # Create a config parser object and read in the file cfgParser = ConfigParser(defaultParams) cfgParser.read(configFile) self.params = {} self.params["cu_dir"] = cfgParser.get("proc_id_model", "cu_dir") self.params["cu_file"] = cfgParser.get("proc_id_model", "cu_file") self.params["thin"] = cfgParser.getint("proc_id_model", "thin") self.params["blockSz"] = cfgParser.getint("cuda", "blockSz") # Parse the params for the spatial GMM model self.params["sigma0"] = cfgParser.getfloat("proc_id_model", "sigma") self.params["kap0"] = cfgParser.getfloat("proc_id_model", "kappa") self.params["nu0"] = cfgParser.getfloat("proc_id_model", "nu") # Parse mu0from config file mu0_str = cfgParser.get("proc_id_model", "mu") if mu0_str == "None": # If not specified, take the mean of the data self.params["mu0"] = np.mean(self.base.data.X, 1) else: # Filter out unwanted characters mu0_str = filter(lambda c: c.isdigit() or c=="," or c=="-" or c==".", mu0_str) self.params["mu0"] = np.fromstring(mu0_str, sep=",",dtype=np.float32) self.params["T0"] = self.params["sigma0"]*np.eye(self.base.data.D) # Parse the desired number of mixture components/processes self.params["K"] = cfgParser.getint("proc_id_model", "K")
def read(self, f): '''Read the settings from the given file handle.''' cfg = ConfigParser() cfg.readfp(f) netSection = 'Network' if cfg.has_section(netSection): if cfg.has_option(netSection, 'defaultIpAddress'): self.defaultIpAddress = cfg.get(netSection, 'defaultIpAddress') if cfg.has_option(netSection, 'defaultPort'): self.defaultPort = cfg.getint(netSection, 'defaultPort') if cfg.has_option(netSection, 'ephemeralPortsFrom'): self.ephemeralPorts[0] = cfg.getint(netSection, 'ephemeralPortsFrom') if cfg.has_option(netSection, 'ephemeralPortsTo'): self.ephemeralPorts[1] = cfg.getint(netSection, 'ephemeralPortsTo') tftpSection = 'TFTP' if cfg.has_section(tftpSection): if cfg.has_option(tftpSection, 'timeout'): self.tftpTimeout = cfg.getfloat(tftpSection, 'timeout') if cfg.has_option(tftpSection, 'retries'): self.tftpRetries = cfg.getint(tftpSection, 'retries') serverSection = 'Server' if cfg.has_section(serverSection): if cfg.has_option(serverSection, 'defaultDirectory'): self.defaultDirectory = cfg.get(serverSection, 'defaultDirectory') if cfg.has_option(serverSection, 'saveLastUsed'): self.saveLastUsed = cfg.getboolean(serverSection, 'saveLastUsed')
def __init__(self, config_filename): locale.setlocale(locale.LC_ALL, '') assert os.path.isfile(config_filename), "Config file not found" local_config_parser = ConfigParser() local_config_parser.read(config_filename) product_info_filename = local_config_parser.get("Config", "info_produtos") self._printer_name = local_config_parser.get("Config", "impressora") assert os.path.isfile(product_info_filename), "Product info file not found" # Set barcode filename self._barcode_filename = os.path.join( os.path.dirname(product_info_filename), "barcode" ) cfg_parser = ConfigParser() cfg_parser.read(product_info_filename) self._primary_categories = dict(cfg_parser.items(self.PRIMARY_CATEGORY_SEC)) self._secondary_categories = dict(cfg_parser.items(self.SECONDARY_CATEGORY_SEC)) if cfg_parser.has_section(self.PRICE_SEC): self.price_list = [] for opt in sorted(cfg_parser.options(self.PRICE_SEC)): self.price_list.append(cfg_parser.getfloat(self.PRICE_SEC, opt)) else: self.price_list = [1.7, 2.21] self._label_header = cfg_parser.get("Label", "header").replace("\\n","\n") self._label_template = cfg_parser.get("Label", "label") self._labels_per_file = 30 self._product_unity = "pç" self._category_on_label = cfg_parser.getint("Geral", "cat_etiqueta")
def __pre_parse(self, opts, args): cp = ConfigParser() self.cp = cp read_files = cp.read(["/etc/xbe/xberc", os.path.expanduser("~/.xbe/xberc"), opts.config]) if not len(read_files): raise CommandFailed("no configuration file found") if opts.timeout is None: opts.timeout = cp.getfloat("network", "timeout") if opts.server is None: opts.server = cp.get("network", "server") if opts.stomp_user is None: opts.stomp_user = cp.get("network", "user") if opts.stomp_pass is None: opts.stomp_pass = cp.get("network", "pass") if opts.user_cert is None: opts.user_cert = os.path.expanduser(cp.get("security", "pubkey")) if opts.user_key is None: opts.user_key = os.path.expanduser(cp.get("security", "privkey")) if opts.ca_cert is None: opts.ca_cert = os.path.expanduser(cp.get("security", "cacert")) from xbe.xml.security import X509Certificate # build the certificate self.user_cert = X509Certificate.load_from_files(opts.user_cert, opts.user_key) self.ca_cert = X509Certificate.load_from_files(opts.ca_cert)
def buttonImportSensors_clicked_cb(self, widget): dialog = gtk.FileChooserDialog("Abrir..", None, gtk.FILE_CHOOSER_ACTION_OPEN, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(dialog.get_current_folder() + "/sensors/") response = dialog.run() if response == gtk.RESPONSE_OK: filename = dialog.get_filename() FILE = open(filename, "r") c = ConfigParser() c.readfp(FILE) name = c.get("SENSOR", "name") unit = c.get("SENSOR", "unit") description = c.get("SENSOR", "description") self.liststore.append([name, unit, description]) sensor = SensorType(name, unit, description, []) self.sensorTypes.append(sensor) for i in c.sections(): if i != "SENSOR": x = c.getint(i, "x") y = c.getfloat(i, "y") sensor.add_point([x, y]) self.writeSensorsConfig() FILE.close() dialog.destroy()
def load_params(self, filename): config = ConfigParser() config.read(filename) self._normalize_config(config) # Input Parameters self._load_config_param(config, 'input', 'semi_major_axis') self._load_config_param(config, 'input', 'star_radius') self._load_config_param(config, 'input', 'planet_radius') self._load_config_param(config, 'input', 'star_temperature') self._load_config_param(config, 'input', 'planet_temperature') self._load_config_param(config, 'input', 'inclination') self._load_config_param(config, 'input', 'darkening_law') self._load_config_param(config, 'input', 'darkening_coefficient_1') self._load_config_param(config, 'input', 'darkening_coefficient_2') self._load_config_param(config, 'input', 'phase_end') self._load_config_param(config, 'input', 'phase_step') self._load_config_param(config, 'input', 'integration_precision') # Import Parameters if config.has_option('import', 'filename') and config.get('import', 'filename'): if '/data/' in config.get('import', 'filename') and config.get('import', 'filename').index('/data/') == 0: self.import_parameters.filename = os.getcwd().replace('\\', '/') + config.get('import', 'filename') else: self.import_parameters.filename = config.get('import', 'filename') self.import_parameters.update_file_label() if config.has_option('import', 'jd2phase') and config.getboolean('import', 'jd2phase') == True : self.import_parameters.hjd_to_phases.setCheckState(Qt.Checked) if config.has_option('import', 'jd2phase_tzero') : self.import_parameters.time_zero.setValue(config.getfloat('import', 'jd2phase_tzero')) if config.has_option('import', 'jd2phase_period') : self.import_parameters.period.setValue(config.getfloat('import', 'jd2phase_period')) if config.has_option('import', 'mag2flux') and config.getboolean('import', 'mag2flux') == True : self.import_parameters.magnitude_to_flux.setCheckState(Qt.Checked) if config.has_option('import', 'mag2flux_mag') : self.import_parameters.magnitude_max.setValue(config.getfloat('import', 'mag2flux_mag')) # Fixes painting bug with range buttons when loading new file # the active ranges stayed active even if they are inactive self.repaint()
def getfloat(self, section, option, default=no_default): try: return ConfigParser.getfloat(self, section, option) except ConfigKeyError: if default is not self.no_default: return default print 'CANNOT FIND CONF KEY', section, option raise
def getfloat(self, section, option, default=NO_DEFAULT): try: return ConfigParser.getfloat(self, section, option) except ConfigKeyError: if default is not self.NO_DEFAULT: return default print "CANNOT FIND CONF KEY", section, option raise
def configfile_parse(args,config_file='swarm.conf'): try: conf_parser=ConfigParser() conf_parser.read(config_file) # output options args.logfile=conf_parser.get("Output","logfile") args.verbose=conf_parser.getboolean("Output","verbose") args.disable_col=conf_parser.getboolean("Output","disable_col") # target options args.target=conf_parser.get("Target","target") args.target_file=conf_parser.get("Target","target_file") if args.target!='': args.target=args.target.split() # swarm options args.swarm=conf_parser.get("Swarm","swarm") args.swarm_file=conf_parser.get("Swarm","swarm_file") args.timeout=conf_parser.getfloat("Swarm","timeout") args.waken_cmd=conf_parser.get("Swarm","waken_cmd") args.m_addr=conf_parser.get("Swarm","m_addr") args.m_port=conf_parser.getint("Swarm","m_port") args.s_port=conf_parser.getint("Swarm","s_port") args.authkey=conf_parser.get("Swarm","authkey") args.sync_data=conf_parser.getboolean("Swarm","sync_data") if args.swarm!='': args.swarm=args.swarm.split() # common options args.process_num=conf_parser.getint("Common","process_num") args.thread_num=conf_parser.getint("Common","thread_num") # domain scan options args.enable_domain_scan=conf_parser.getboolean("Domain Scan","enable_domain_scan") args.domain_compbrute=conf_parser.getboolean("Domain Scan","domain_compbrute") args.domain_dict=conf_parser.get("Domain Scan","domain_dict") args.domain_maxlevel=conf_parser.getint("Domain Scan","domain_maxlevel") args.domain_charset=conf_parser.get("Domain Scan","domain_charset") args.domain_levellen=conf_parser.get("Domain Scan","domain_levellen") args.domain_timeout=conf_parser.getfloat("Domain Scan","domain_timeout") except Exception,e: print 'parse config file error' raise SwarmUseException('parse config file error')
def parse_input(config_file): config = ConfigParser() config.read(config_file) # get params from file, using test values as defaults if missing options lambd = ( config.getfloat("Material Parameters", "lambd") if config.has_option("Material Parameters", "lambd") else 0.5 ) mu = config.getfloat("Material Parameters", "mu") if config.has_option("Material Parameters", "mu") else 1.0 rho = config.getfloat("Material Parameters", "rho") if config.has_option("Material Parameters", "rho") else 3.0 min_x = config.getfloat("Coordinates", "min_x") if config.has_option("Coordinates", "min_x") else 0.0 max_x = config.getfloat("Coordinates", "max_x") if config.has_option("Coordinates", "max_x") else 5.0 min_y = config.getfloat("Coordinates", "min_y") if config.has_option("Coordinates", "min_y") else 0.0 max_y = config.getfloat("Coordinates", "max_y") if config.has_option("Coordinates", "max_y") else 5.0 min_z = config.getfloat("Coordinates", "min_z") if config.has_option("Coordinates", "min_z") else 0.0 max_z = config.getfloat("Coordinates", "max_z") if config.has_option("Coordinates", "max_z") else 5.0 N_x = config.getint("Grid Points", "N_x") if config.has_option("Grid Points", "N_x") else 100 N_y = config.getint("Grid Points", "N_y") if config.has_option("Grid Points", "N_y") else 100 N_z = config.getint("Grid Points", "N_z") if config.has_option("Grid Points", "N_z") else 100 t_0 = config.getfloat("Time Parameters", "t_0") if config.has_option("Time Parameters", "t_0") else 0.0 t_f = config.getfloat("Time Parameters", "t_f") if config.has_option("Time Parameters", "t_f") else 2.5 N_t = config.getint("Time Parameters", "N_t") if config.has_option("Time Parameters", "N_t") else 100 output = config.get("Output File", "data") if config.has_option("Output File", "data") else "output.dat" return lambd, mu, rho, min_x, max_x, min_y, max_y, min_z, max_z, N_x, N_y, N_z, t_0, t_f, N_t, output
class ConfigFile(): """ Adapted from a helper method from Python Wiki. This class will hold a config file, and attempt to automatically convert values to ints or booleans. With example.ini as a test file: >>> c = ConfigFile('tests/example.ini') >>> c.get('Section One', 'Key') 'Value' >>> c.get('Section One', 'Luggage_Combination') 12345 >>> c.getsection('Section Two') {'LOCATION': 'Hyrule', 'KEY': 'Value'} """ def __init__(self, path): self.conf = ConfigParser() self.conf.read(path) def getsection(self, section): """ Returns an entire section in a dict. The dict's keys will be uppercase, for convenience. """ keys = {} try: options = self.conf.options(section) except: return {} for opt in options: key = opt.upper() try: keys[key] = self.get(section, opt) except: keys[key] = None return keys def get(self, section, opt): """ Gets a config value. This value will automatically be converted to a boolean, float or int. """ try: key = self.conf.get(section, opt) if key == 'True': return True elif key == 'False': return False elif re.match('^[0-9]+$', key): return self.conf.getint(section, opt) elif re.match('^[0-9]+\.[0-9]+$', key): return self.conf.getfloat(section, opt) else: return key except: return None
def parseConfigurationFile(self, configFile): # Create a config parser object and read in the file defaultParams = {} cfgParser = ConfigParser(defaultParams) cfgParser.read(configFile) self.params = {} self.params["dt_max"] = cfgParser.getfloat("preprocessing", "dt_max")
class Config(object): """ Parses a .ini configuration file This parser disregards sections, meaning option names are unique >>> fcc = Config("config.ini") >>> fcc["docsFileDir"] "specific_doc_file.txt" """ def __init__(self, configFName): self.confPar = ConfigParser() self.confPar.read(configFName) self.confDict = {} self.options = set() self.readConfig() def readConfig(self): """ Hard coded reading of options to ensure correct data type""" # for section in self.configParser.sections(): # for option in self.configParser.options(section): # self.configDict[option] = self.configParser.get(section, option) self.readConfigHelper("Files", "seedFile") self.readConfigHelper("Files", "blacklistFile") self.readConfigHelper("Files", "trainingDocs") self.readConfigHelper("Model", "useVSM", "boolean") self.readConfigHelper("VSM Filtering", "VSMFilterModel") self.readConfigHelper("VSM Filtering", "minRepositoryDocNum", "int") self.readConfigHelper("VSM Filtering", "filterRelevantThreshold", "float") self.readConfigHelper("VSM Filtering", "filterIrrelevantThreshold", "float") self.readConfigHelper("VSM Filtering", "numFilterTopics", "int") self.readConfigHelper("Classifier", "classifier") self.readConfigHelper("Classifier", "allowAdaptive", "boolean") self.readConfigHelper("Crawling", "pageLimit", "int") self.readConfigHelper("Crawling", "linkLimit", "int") self.readConfigHelper("Crawling", "relevantThreshold", "float") def readConfigHelper(self, sect, opt, dataType="string"): """ Helper function to read in an option, based on dataType """ if dataType.lower() == "string": self.confDict[opt] = self.confPar.get(sect, opt) elif dataType.lower() == "boolean": self.confDict[opt] = self.confPar.getboolean(sect, opt) elif dataType.lower() == "float": self.confDict[opt] = self.confPar.getfloat(sect, opt) elif dataType.lower() == "int": self.confDict[opt] = self.confPar.getint(sect, opt) self.options.add(opt) def __getitem__(self, key): return self.confDict[key] def getOptions(self): return self.options