def load_from_file(): config = OctoPiControlPanelConfig() cfg = RawConfigParser() config.script_directory = os.path.dirname(os.path.realpath(__file__)) settings_file_path = os.path.join(config.script_directory, "OctoPiControlPanelConfig.cfg") cfg.readfp(open(settings_file_path, "r")) config.api_baseurl = cfg.get('settings', 'baseurl') config.apikey = cfg.get('settings', 'apikey') config.updatetime = cfg.getint('settings', 'updatetime') config.backlightofftime = cfg.getint('settings', 'backlightofftime') if cfg.has_option('settings', 'width'): config.width = cfg.getint('settings', 'width') else: config.width = 320 if cfg.has_option('settings', 'height'): config.height = cfg.getint('settings', 'height') else: config.height = 240 if cfg.has_option('settings', 'caption'): config.caption = cfg.get('settings', 'caption') else: config.caption = "OctoPiControlPanelConfig" return config
def __read_config(self): """ Obtiene la configuración de la persona de su archivo .person y devuelve True si es válida """ parser = RawConfigParser() with codecs.open("config/" + self.person + '.person', 'r', encoding='utf-8') as f: parser.readfp(f) if parser.has_section("web_bug"): if parser.has_option("web_bug", 'search_terms'): self.__search_terms = parser.get("web_bug", 'search_terms') if self.__search_terms == '': return False else: return False if parser.has_option("web_bug", 'weight'): self.__weight = parser.getint("web_bug", 'weight') if parser.has_option("web_bug", 'weight_no_search_terms'): self.__weight_no_search_terms = parser.getint( "web_bug", 'weight_no_search_terms') if parser.has_option("web_bug", 'weight_visit'): self.__weight_visit = parser.getint("web_bug", 'weight_visit') if parser.has_option("web_bug", 'webbug_log'): self.__webbug_log =\ [e.strip() for e in parser.get("web_bug", 'webbug_log').split(',')] if self.__webbug_log == ['']: return False else: return False else: return False return True
def __init__(self, parent, child, level): self.parent = parent self.child = child self.level = level parser = urlparse(parent) self.parent_domain = parser.hostname parser = urlparse(child) self.child_domain = parser.hostname self.list_host = [] config = RawConfigParser() config.read('./config/Config.ini') self.area_inside = config.getint('Initialization', 'area_inside') self.area_outside = config.getint('Initialization', 'area_outside') num_host = config.getint('Initialization', 'number_of_host') for i in range(num_host): hostname = 'Host' + (str)(i + 1) host = config.get(hostname, 'domain') self.list_host.append(host) self.parent_area = '' self.child_area = '' for i in self.list_host: if i == self.parent_domain: self.parent_area = 'Inside' break else: self.parent_area = 'Outside' for i in self.list_host: if i == self.child_domain: self.child_area = 'Inside' break else: self.child_area = 'Outside'
def read_config(filename): ''' Read in the user configuation file.''' user_config = { 'user_call': 'HORUS_RX', 'freedv_udp_port': 55690, 'ozi_udp_port': 55683, 'summary_port': 55672, 'station_lat': 0.0, 'station_lon': 0.0, 'radio_comment': "", 'antenna_comment': "" } try: config = RawConfigParser() config.read(filename) user_config['user_call'] = config.get('user', 'callsign') user_config['station_lat'] = config.getfloat('user', 'station_lat') user_config['station_lon'] = config.getfloat('user', 'station_lon') user_config['radio_comment'] = config.get('user', 'radio_comment') user_config['antenna_comment'] = config.get('user', 'antenna_comment') user_config['freedv_udp_port'] = config.getint('freedv', 'udp_port') user_config['ozi_udp_port'] = config.getint('ozimux', 'ozimux_port') user_config['summary_port'] = config.getint('ozimux', 'summary_port') return user_config except: traceback.print_exc() logging.error( "Could not parse config file, exiting. Have you copied user.cfg.example to user.cfg?" ) return None
def parse_items(): """Parses the items.ini file.""" global ITEMS raws = RawConfigParser(item_defaults, allow_no_value=True) raws.read('items.ini') for section in raws.sections(): ITEMS[section] = {} ITEMS[section]['name'] = section ITEMS[section]['slot'] = raws.get(section, 'slot') damage = re.split( r'\D+', raws.get(section, 'damage') ) if len(damage) >= 2: damage = map(int, damage) ITEMS[section]['damage'] = damage else: #turn list to int if only one value ITEMS[section]['damage'] = int(damage[0]) ITEMS[section]['defense'] = raws.getint(section, 'defense') ITEMS[section]['weight'] = raws.getint(section, 'weight') ITEMS[section]['char'] = raws.get(section, 'symbol') assert len(ITEMS[section]['char']) == 1 #seperates the color values and converts them into the libtcod standard color_tuple = re.split( r'\D+', raws.get(section, 'color') ) color_tuple = map(int, color_tuple) ITEMS[section]['color'] = libtcod.Color( *color_tuple ) print ITEMS
def __read_config(self): """ Obtiene la configuración de la persona de su archivo .person y devuelve True si es válida """ parser = RawConfigParser() with codecs.open("config/" + self.person + '.person', 'r', encoding='utf-8') as f: parser.readfp(f) if parser.has_section("web_bug"): if parser.has_option("web_bug", 'search_terms'): self.__search_terms = parser.get("web_bug", 'search_terms') if self.__search_terms == '': return False else: return False if parser.has_option("web_bug", 'weight'): self.__weight = parser.getint("web_bug", 'weight') if parser.has_option("web_bug", 'weight_no_search_terms'): self.__weight_no_search_terms = parser.getint("web_bug", 'weight_no_search_terms') if parser.has_option("web_bug", 'weight_visit'): self.__weight_visit = parser.getint("web_bug", 'weight_visit') if parser.has_option("web_bug", 'webbug_log'): self.__webbug_log =\ [e.strip() for e in parser.get("web_bug", 'webbug_log').split(',')] if self.__webbug_log == ['']: return False else: return False else: return False return True
def __init__(self, filename, mixer): from ConfigParser import RawConfigParser config = RawConfigParser() config.read(filename) self.play_intro = config.getboolean('Main', 'play_intro') if mixer: self.mixer = config.getboolean('Main', 'mixer') else: self.mixer = False self.music = GetDataPath(config.get('Main', 'music')) self.music = os.path.expanduser(self.music) width = config.getint('Defaults', 'width') height = config.getint('Defaults', 'height') self.subsettings = {} sections = config.sections() for defaults in ('Main', 'Defaults'): sections.remove(defaults) for sec in sections: op_dict = {} for op in config.options(sec): op_dict[op] = config.get(sec, op) if op in ('width', 'height'): op_dict[op] = eval(op_dict[op]) for op in ('width', 'height'): if op not in op_dict or op_dict[op] == 0: op_dict[op] = locals()[op] self.subsettings[sec] = op_dict
def __init__(self, configuration_file, rewrite=False): parser = RawConfigParser() parser.read(configuration_file) dist_filename = parser.get('files', 'distances-filename') entropy_filename = parser.get('files', 'entropy-filename') self.mRMR_filename = parser.get('files', 'mRMR-filename') self.num_bins = parser.getint('parameters', 'num-bins') self.bin_width = parser.getfloat('parameters', 'bin-width') self.aa = parser.getboolean('parameters', 'aa') self.chains = parser.getint('parameters', 'chains') self.dist_range = [float(i) for i in parser.get('parameters', 'distance-range').split()] self.weights = [float(i) for i in parser.get('parameters', 'weights').split()] self.resi_select = parser.get('parameters', 'excluded-residues').split() if not self.resi_select: self.resi_select = None print "Loading distance file %s" % dist_filename init = time.time() self.dists = cPickle.load(open(dist_filename)) print "Loaded %s in %f seconds" % (dist_filename, time.time() - init) # If no entropy has been provided, entropy must be calculated for permitted residues. print colors.HEADER + "\tENTROPY CALCULATION" + colors.ENDC if os.path.exists(entropy_filename) and not rewrite: warn_file_exists(entropy_filename) self.entropy = cPickle.load(open(entropy_filename)) else: print "No entropy file was found or you have chosen to rewrite. Calculating entropies..." self.entropy = h_fast(self.dists) print "Dumping entopies to", entropy_filename cPickle.dump(self.entropy, open(entropy_filename, 'w'))
def getprefs(configfile, tkobj, PERSIST): # To keep things simple for possible future preference additions/deletions: # Try to stick to - TK Widget name = prefs dictionary key = ini.get|set name. # EX: mobipath = prefs['mobipath'] = config.get('Defaults', mobipath). prefs = {} # Sane defaults prefs['mobipath'] = os.getcwdu() prefs['outpath'] = os.getcwdu() prefs['apnxpath'] = os.getcwdu() prefs['splitvar'] = 0 prefs['rawvar'] = 0 prefs['dbgvar'] = 0 prefs['hdvar'] = 0 prefs['epubver'] = 0 tkobj.update_idletasks() w = tkobj.winfo_screenwidth() h = tkobj.winfo_screenheight() rootsize = (605, 575) x = w / 2 - rootsize[0] / 2 y = h / 2 - rootsize[1] / 2 prefs['windowgeometry'] = (u'%dx%d+%d+%d' % (rootsize + (x, y))) if os.path.exists(configfile) and PERSIST: config = RawConfigParser() try: with codecs.open(configfile, 'r', 'utf-8') as f: config.readfp(f) except: return prefs # Python 2.x's ConfigParser module will not save unicode strings to an ini file (at least on Windows) # no matter how hard you try to smack it around and scare it into doing so. # The workaround (to support unicode path prefences) is to encode the file path using the # unicode_escape 'codec' when writing, and to decode using the unicode_escape codec when reading. if config.has_option('Defaults', 'mobipath'): prefs['mobipath'] = config.get('Defaults', 'mobipath').decode('unicode_escape') if config.has_option('Defaults', 'outpath'): prefs['outpath'] = config.get('Defaults', 'outpath').decode('unicode_escape') if config.has_option('Defaults', 'apnxpath'): prefs['apnxpath'] = config.get('Defaults', 'apnxpath').decode('unicode_escape') if config.has_option('Defaults', 'splitvar'): prefs['splitvar'] = config.getint('Defaults', 'splitvar') if config.has_option('Defaults', 'rawvar'): prefs['rawvar'] = config.getint('Defaults', 'rawvar') if config.has_option('Defaults', 'dbgvar'): prefs['dbgvar'] = config.getint('Defaults', 'dbgvar') if config.has_option('Defaults', 'hdvar'): prefs['hdvar'] = config.getint('Defaults', 'hdvar') if config.has_option('Defaults', 'epubver'): prefs['epubver'] = config.getint('Defaults', 'epubver') if config.has_option('Geometry', 'windowgeometry'): prefs['windowgeometry'] = config.get('Geometry', 'windowgeometry') return prefs
def initialize_from_config(self): """ Initializes the scene using parameters set in the config file """ cfg = RawConfigParser() cfg.readfp(open('./Config/generation.conf')) self.height = cfg.getint("scene", "height") self.width = cfg.getint("scene", "width") self.num_objects = cfg.getint("scene", "num_objects") self.save()
def readFile2(path): config = RawConfigParser() config.read(path) nbits = config.getint('SIGNAL', 'nbits') rate = config.getint('SIGNAL', 'rate') dataString = config.get('SIGNAL', 'data').split('\n') data = map(int, dataString) return nbits, rate, data
def readFile(path): config = RawConfigParser() config.read(path) nbits = config.getint('INFO', 'nbits') rate = config.getint('INFO', 'rate') elements = config.getint('INFO', 'elements') output = [map(int, config.get('SIGNAL-%d' % i, 'data').split('\n')) for i in xrange(elements)] return nbits, rate, output
def getprefs(configfile, tkobj, PERSIST): # To keep things simple for possible future preference additions/deletions: # Try to stick to - TK Widget name = prefs dictionary key = ini.get|set name. # EX: mobipath = prefs['mobipath'] = config.get('Defaults', mobipath). prefs = {} # Sane defaults prefs['mobipath'] = os.getcwdu() prefs['outpath'] = os.getcwdu() prefs['apnxpath'] = os.getcwdu() prefs['splitvar'] = 0 prefs['rawvar'] = 0 prefs['dbgvar'] = 0 prefs['hdvar'] = 0 prefs['epubver'] = 0 tkobj.update_idletasks() w = tkobj.winfo_screenwidth() h = tkobj.winfo_screenheight() rootsize = (605, 575) x = w/2 - rootsize[0]/2 y = h/2 - rootsize[1]/2 prefs['windowgeometry'] = (u'%dx%d+%d+%d' % (rootsize + (x, y))) if os.path.exists(configfile) and PERSIST: config = RawConfigParser() try: with codecs.open(configfile, 'r', 'utf-8') as f: config.readfp(f) except: return prefs # Python 2.x's ConfigParser module will not save unicode strings to an ini file (at least on Windows) # no matter how hard you try to smack it around and scare it into doing so. # The workaround (to support unicode path prefences) is to encode the file path using the # unicode_escape 'codec' when writing, and to decode using the unicode_escape codec when reading. if config.has_option('Defaults', 'mobipath'): prefs['mobipath'] = config.get('Defaults', 'mobipath').decode('unicode_escape') if config.has_option('Defaults', 'outpath'): prefs['outpath'] = config.get('Defaults', 'outpath').decode('unicode_escape') if config.has_option('Defaults', 'apnxpath'): prefs['apnxpath'] = config.get('Defaults', 'apnxpath').decode('unicode_escape') if config.has_option('Defaults', 'splitvar'): prefs['splitvar'] = config.getint('Defaults', 'splitvar') if config.has_option('Defaults', 'rawvar'): prefs['rawvar'] = config.getint('Defaults', 'rawvar') if config.has_option('Defaults', 'dbgvar'): prefs['dbgvar'] = config.getint('Defaults', 'dbgvar') if config.has_option('Defaults', 'hdvar'): prefs['hdvar'] = config.getint('Defaults', 'hdvar') if config.has_option('Defaults', 'epubver'): prefs['epubver'] = config.getint('Defaults', 'epubver') if config.has_option('Geometry', 'windowgeometry'): prefs['windowgeometry'] = config.get('Geometry', 'windowgeometry') return prefs
def load_config(self): config = RawConfigParser({ 'min_fhr': 0, 'max_fhr': 180, 'delta_fhr': 6 }) config.read( os.path.join(os.path.abspath(os.path.dirname(__file__)), 'model_config.cfg')) # self.fname_template = config.get(self.model_name, 'fname_template') self.min_fhr = config.getint(self.model_name, 'min_fhr') self.max_fhr = config.getint(self.model_name, 'max_fhr') + 1 self.delta_fhr = config.getint(self.model_name, 'delta_fhr')
def load_config(self, filename): """ Loads configuration settings from the file whose name is given. It will read the section called "servo.[name]", where [name] is the name of this servo as given to the constructor. @param filename: the name of the config file to be read """ cfg = RawConfigParser(); cfg.read(filename) section = "servo.%s" % self._name self._id = cfg.getint(section, "id") self._min = cfg.getint(section, "min") self._center = cfg.getint(section, "center") self._max = cfg.getint(section, "max")
def load_config(self, filename): """ Loads configuration settings from the file whose name is given. It will read the section called "servo.[name]", where [name] is the name of this servo as given to the constructor. @param filename: the name of the config file to be read """ cfg = RawConfigParser() cfg.read(filename) section = "servo.%s" % self._name self._id = cfg.getint(section, "id") self._min = cfg.getint(section, "min") self._center = cfg.getint(section, "center") self._max = cfg.getint(section, "max")
def next_replica(serial_file=CA_SERIALNO): """ Return the starting serial number for a new self-signed replica """ fp = None parser = RawConfigParser() if ipautil.file_exists(serial_file): try: fp = open(serial_file, "r+") fcntl.flock(fp.fileno(), fcntl.LOCK_EX) parser.readfp(fp) serial = parser.getint('selfsign', 'nextreplica') nextreplica = serial + parser.getint('selfsign', 'replicainterval') except IOError, e: raise RuntimeError("Unable to determine serial number: %s" % str(e))
def main(): """Main console script function. Runs an operational bot on a specific room list which is defined in the command line. """ config = RawConfigParser(DEFAULT_CONFIG) if len(sys.argv) < 2 or not os.path.isfile(sys.argv[1]): print >> sys.stderr, "usage: whistler <config>" return 1 try: config.read(sys.argv[1]) except: print >> sys.stderr, "unable to read config file %s." % sys.argv[1] return 1 mixins = map(lambda x:x[6:], filter(lambda x:x[0:6] == "mixin:", config.sections())) rooms = map(lambda x:x[5:], filter(lambda x:x[0:5] == "room:", config.sections())) factory = BotFactory(dict([(x, dict(get_no_defaults(config,"mixin:%s" % x))) for x in mixins])) logging.basicConfig( level=config.getint("DEFAULT", "loglevel"), format="[%(asctime)s] %(levelname)s: %(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) Bot = factory(mixins) bot = Bot( jid = config.get("DEFAULT", "account"), password = config.get("DEFAULT", "password"), resource = config.get("DEFAULT", "resource"), mention = config.get("DEFAULT", "mention"), use_tls = config.get("DEFAULT", "use_tls"), users = set(config.get("DEFAULT", "users").split(",")), server = ( config.get("DEFAULT", "server"), config.getint("DEFAULT", "port") ), rooms = rooms, ignore_ssl_cert = config.get("DEFAULT", "ignore_ssl_cert") ) try: bot.start() except KeyboardInterrupt: bot.stop()
def __init__(self): for file in ('', ): if os.path.exists(file): break else: file = None if file is None: reactor.callWhenRunning( log.msg, 'No config loaded, use default settings' ) else: with open(file, 'rb') as fp: parser = ConfigParser(); parser.readfp(fp) for section in parser.sections(): for key, value in parser.items(section): key, value = key.lower(), value.decode('utf8') if section == 'general': if key in ( 'timeout','connectionslimit',): value and setattr(self, key, parser.getint(section, key)) elif key in ( 'socksauth',): setattr(self, key, parser.getboolean(section, key)) elif key in ( 'usersfile','listeninterface',): value and setattr(self, key, parser.get(section, key)) else: raise ParsingError, 'unknown key "%s" in section "%s"' % (key, section) else: raise TypeError, 'unknown section "%s"' % (section)
def get_license_devices(): """ Retrieves the number of assets for a given license Return: Number of devices signed for a license 0 if an error occurs 1000000 if 'devices' is not specified in the ossim.lic file """ rc, pro = system_is_professional() devices = 0 if rc and pro: if os.path.isfile("/etc/ossim/ossim.lic"): try: config = RawConfigParser() license_file = config.read('/etc/ossim/ossim.lic') devices = config.getint('appliance', 'devices') except NoOptionError: devices = 1000000 else: api_log.debug( "License devices can't be determined: License file not found") devices = 0 else: devices = 1000000 return devices
def _getPostgresDBCursor(conffile): # Read the database connection settings from the configuration file. cp = RawConfigParser() res = cp.read(conffile) if len(res) == 0: raise ConfigError('The database configuration file ' + conffile + ' could not be read.') dbhost = cp.get('database', 'host') dbport = cp.getint('database', 'port') dbuser = cp.get('database', 'user') dbpw = cp.get('database', 'pw') dbname = cp.get('database', 'dbname') dbschema = cp.get('database', 'schema') # Set up the database connection, get a connection cursor, and set the default schema. conn = ppg2.connect(host=dbhost, port=dbport, user=dbuser, password=dbpw, database=dbname) pgcur = conn.cursor() pgcur.execute('SET search_path TO ' + dbschema) return pgcur
class Config: BLINDS = 0 BLINDX = 1 WEB = 2 SECTIONS = ["blinds", "blind_%d", "webServer"] STRING_KEYS = [ "msgFormat", "logFileName", "endPoint", "webRoot", "default", "name", "tag", "address", "cmdDriveIn", "cmdDriveOut", "cmdStop", "headline" ] INT_KEYS = ["maxFilesize", "logLevel", "count"] BOOLEAN_KEYS = ["enableLogging"] DEFAULTS = { "enableLogging": "yes", "logFileName": "/tmp/pbc.log", "maxFilesize": 1000000, "msgFormat": "%(asctime)s, %(levelname)s, %(module)s {%(process)d}, %(lineno)d, %(message)s", "logLevel": 10 } def __init__(self, cfgFile, section): self.section = section self.cfg = RawConfigParser(Config.DEFAULTS) _ = self.cfg.read(cfgFile) def hasKey(self, dct, key): k = key.upper() for d in dct: if d.upper() == k: return d return None def hasSection(self, section): return self.cfg.has_section(section) def hasOption(self, option): return self.cfg.has_option(self.section, option) def __getattr__(self, name): key = self.hasKey(Config.STRING_KEYS, name) if not key is None: return self.cfg.get(self.section, key) key = self.hasKey(Config.INT_KEYS, name) if not key is None: return self.cfg.getint(self.section, key) key = self.hasKey(Config.BOOLEAN_KEYS, name) if not key is None: return self.cfg.getboolean(self.section, key) return None def setSection(self, newSection): tmp = self.section self.section = newSection return tmp def readValue(self, key): return self.cfg.get(self.section, key)
class Configuration: def __init__(self, configfile): config_home = os.getenv("CONF_HOME") if config_home: self._configFile = "%s/%s" % (config_home, configfile) else: self._configFile = configfile self._genConf() def _setConfigFile(self, configFile=None): """设置configure文件""" self._configFile = configFile if not self._configFile: raise Exception("配置文件不存在") self._genConf() def _genConf(self): if not self._configFile: raise Exception("没有配置文件") self._config = RawConfigParser() self._config.read(self._configFile) def get(self, sect, opt, default=None): if self._config.has_option(sect, opt): return self._config.get(sect, opt) return default def getint(self, sect, opt, default=None): if self._config.has_option(sect, opt): return self._config.getint(sect, opt) return default def items(self, sect): return self._config.items(sect)
def render_POST(self, request): def _renderResponse(response): if isinstance(response, Failure): request.write(json.dumps({'success': False, 'message': response.getErrorMessage()})) else: request.write(json.dumps({'success': True})) request.finish() content = parse_qs(request.content.read()) command = content.get('playlist.add', [None])[0] item = content['item'][0] config_parser = RawConfigParser() config_parser.read(os.path.expanduser("~/.config/smplayer/smplayer.ini")) port = config_parser.getint('instances', 'temp\\autoport') creator = ClientCreator(reactor, SMPlayer, item = item) creator.connectTCP('127.0.0.1', port).addBoth(_renderResponse) request.setHeader('Access-Control-Allow-Origin', '*') request.setHeader('Content-Type', 'application/json') return NOT_DONE_YET
def _parse_legacy_config_file(self): """ Parse a legacy configuration file. """ conf = RawConfigParser() conf.read(LEGACY_CONFIG_FILE) styles = self.styles.copy() if conf.has_option('params', 'dm_template'): styles['dm_template'] = conf.get('params', 'dm_template') if conf.has_option('params', 'header_template'): styles['header_template'] = conf.get('params', 'header_template') self.styles.update(styles) if conf.has_option('params', 'logging_level'): self.logging_level = conf.getint('params', 'logging_level') for binding in self.key_bindings: if conf.has_option('keys', binding): custom_key = conf.get('keys', binding) self._set_key_binding(binding, custom_key) palette_labels = [color[0] for color in PALETTE] for label in palette_labels: if conf.has_option('colors', label): custom_fg = conf.get('colors', label) self._set_color(label, custom_fg)
def loadConfiguration(facebookConfigFilename='facebook-monitor.cfg'): print colorama.Fore.CYAN + infoPrefix + 'Loading Configuration File' + colorama.Fore.RESET dictConfig = dict() parser = RawConfigParser() parser.read(facebookConfigFilename) dictConfig['access_token'] = parser.get('auth', 'access_token') dictConfig['page_info_url_keyword'] = parser.get('page_info', 'page_info_url_keyword') dictConfig['page_info_token_keyword'] = parser.get( 'page_info', 'page_info_token_keyword') dictConfig['page_info_pattern'] = parser.get('page_info', 'page_info_pattern') dictConfig['page_info_targets'] = parser.get( 'page_info', 'page_info_targets').split(',') dictConfig['page_info_interval'] = parser.getint( 'page_info', 'page_info_interval') # secs dictConfig['page_info_out'] = parser.get('page_info', 'page_info_out') dictConfig['page_info_deadline'] = parser.get('page_info', 'page_info_deadline') try: dictConfig['page_info_deadline'] = datetime.datetime.strptime( dictConfig['page_info_deadline'], '%Y-%m-%d %H:%M:%S') except ValueError: dictConfig['page_info_deadline'] = datetime.datetime.now( ) + datetime.timedelta(days=(365 * 10)) # lol hahahaha return dictConfig
def __read_config(self): """ Obtiene la configuración de la persona de su archivo .person y devuelve True si es válida """ parser = RawConfigParser() with codecs.open("config/" + self.person + '.person', 'r', encoding='utf-8') as f: parser.readfp(f) if parser.has_section("metadata_crawling"): if parser.has_option('metadata_crawling', 'files'): self.__files =\ [e.strip() for e in parser.get('metadata_crawling', 'files').split(',')] if self.__files == ['']: return False else: return False if parser.has_option('metadata_crawling', 'weight'): self.__weight = parser.getint('metadata_crawling', 'weight') if parser.has_option('metadata_crawling', 'access_log'): self.__access_log = parser.get('metadata_crawling', 'access_log') if not self.__access_log: return False else: return False if parser.has_option('metadata_crawling', 'access_log_format'): self.__access_log_format = parser.get('metadata_crawling', 'access_log_format') if not self.__access_log_format: return False else: return False else: return False return True
def parse_conf(conf_fd): """Parse configuration file""" config = RawConfigParser() config.readfp(conf_fd) try: settings = { 'host_ip': config.get('main', 'host_ip'), 'runtime': config.getint('main', 'runtime'), 'timeout': config.getint('main', 'timeout'), 'use_sudo': config.getboolean('main', 'use_sudo'), 'rekall': config.get('main', 'rekall'), 'xml_conf': config.get('main', 'xml_conf'), 'vol_bin': config.get('main', 'vol_bin'), 'vol_prof': config.get('main', 'vol_prof'), } except (NoOptionError, ValueError) as e: log.error('Configuration is missing parameters. See example.conf.') sys.exit(1) errors = False for filepath in ['rekall', 'xml_conf']: if not os.path.isfile(settings[filepath]): log.error('Not a file: ' + str(settings[filepath])) errors = True if errors: log.error('Config file contains errors') sys.exit(1) return settings
def __read_config(self): """ Obtiene la configuración de la persona de su archivo .person y devuelve True si es válida """ pparser = RawConfigParser() with codecs.open("config/" + self.person + '.person', 'r', encoding='utf-8') as cf: pparser.readfp(cf) if pparser.has_section("general"): if pparser.has_option('general', 'name'): self.name = pparser.get('general', 'name') if self.name == '': return False else: return False if pparser.has_option('general', 'notify'): self.notify = pparser.getboolean('general', 'notify') if pparser.has_option('general', 'alarm_threshold'): self.alarm_threshold = pparser.getint( 'general', 'alarm_threshold') if pparser.has_option('general', 'email'): self.email = pparser.get('general', 'email') if self.email == '' and self.notify: return False else: return False return True
def __read_config(self): """ Obtiene la configuración de la persona de su archivo .person y devuelve True si es válida """ pparser = RawConfigParser() with codecs.open("config/" + self.person + '.person', 'r', encoding='utf-8') as cf: pparser.readfp(cf) if pparser.has_section("general"): if pparser.has_option('general', 'name'): self.name = pparser.get('general', 'name') if self.name == '': return False else: return False if pparser.has_option('general', 'notify'): self.notify = pparser.getboolean('general', 'notify') if pparser.has_option('general', 'alarm_threshold'): self.alarm_threshold = pparser.getint('general', 'alarm_threshold') if pparser.has_option('general', 'email'): self.email = pparser.get('general', 'email') if self.email == '' and self.notify: return False else: return False return True
class Configuration(object): """ Singleton class to access application's configuration. """ def __init__(self): self.parser = RawConfigParser() config_file = os.path.join(get_install_dir(), 'config.ini') self.parser.read(config_file) def get(self, section, option): return self.parser.get(section, option) def getboolean(self, section, option): return self.parser.getboolean(section, option) def getfloat(self, section, option): return self.parser.getfload(section, option) def getint(self, section, option): return self.parser.getint(section, option) def has_option(self, section, option): return self.parser.has_option(section, option) def has_section(self, section): return self.parser.has_section(section)
def get_license_devices(): """ Retrieves the number of assets for a given license Return: Number of devices signed for a license 0 if an error occurs 1000000 if 'devices' is not specified in the ossim.lic file """ rc, pro = system_is_professional() devices = 0 if rc and pro: if os.path.isfile("/etc/ossim/ossim.lic"): try: config = RawConfigParser() license_file = config.read('/etc/ossim/ossim.lic') devices = config.getint('appliance', 'devices') except NoOptionError: devices = 1000000 else: api_log.debug("License devices can't be determined: License file not found") devices = 0 else: devices = 1000000 return devices
def next_serial(serial_file=CA_SERIALNO): """ Get the next serial number if we're using an NSS-based self-signed CA. The file is an ini-like file with following properties: lastvalue = the last serial number handed out nextreplica = the serial number the next replica should start with replicainterval = the number to add to nextreplica the next time a replica is created File locking is attempted so we have unique serial numbers. """ fp = None parser = RawConfigParser() if ipautil.file_exists(serial_file): try: fp = open(serial_file, "r+") fcntl.flock(fp.fileno(), fcntl.LOCK_EX) parser.readfp(fp) serial = parser.getint('selfsign', 'lastvalue') cur_serial = serial + 1 except IOError, e: raise RuntimeError("Unable to determine serial number: %s" % str(e)) except MissingSectionHeaderError: fcntl.flock(fp.fileno(), fcntl.LOCK_UN) fp.close() f=open(serial_file,"r") r = f.readline() f.close() cur_serial = int(r) + 1 fp = open(serial_file, "w") fcntl.flock(fp.fileno(), fcntl.LOCK_EX) parser.add_section('selfsign') parser.set('selfsign', 'nextreplica', 500000) parser.set('selfsign', 'replicainterval', 500000)
def main(): print "reading configuration" logging.basicConfig() config = RawConfigParser() config.read(['SystemInfoJabberBot.cfg',expanduser('~/.config/SystemInfoJabberBot.cfg')]) username = config.get('systembot','username') password = config.get('systembot','password') auth_users_raw= config.get('systembot','auth_users') auth_users=auth_users_raw.replace(' ','').split(',') print "set config" bot = SystemInfoJabberBot(username,password,auth_users) # Transmission config if config.has_section('transmissionrpc'): host = config.get('transmissionrpc','host') port = config.getint('transmissionrpc','port') try: user = config.get('transmissionrpc','user') psw = config.get('transmissionrpc','password') bot.setTransmissionConfig(host,port=port,user=user,psw=psw) except NoOptionError: bot.setTransmissionConfig(host,port=port) if config.has_section('logs'): log_files=config.items('logs') bot.setLogFiles( dict(log_files) ) print "start serve" bot.serve_forever() try: bot.quit() except Exception: pass
def __init__(self, *args): LoginAction.__init__(self, *args) self.set_values(DEFAULT_VALS) self.LOG = self.db.get_logger().getChild('ldap_auth') ldap_conf_file = os.path.join(self.db.config.ext['HOME'], 'ldap_config.ini') if os.path.exists(ldap_conf_file): self.LOG.debug("Reading configuration file 'ldap_config.ini'") cfg = RawConfigParser() cfg.read(ldap_conf_file) if cfg.has_section('ldap'): for (key, value) in cfg.items('ldap'): self.LOG.debug("Setting option %s to %s" % (key, value)) if key in ['use_local_auth', 'autocreate', 'bind_once']: setattr(self, key, cfg.getboolean('ldap', key)) elif key in ['referrals', 'start_tls', 'timeout']: setattr(self, key, cfg.getint('ldap', key)) elif key == 'debug' and cfg.getboolean('ldap', key): self.LOG.setLevel(logging.DEBUG) else: setattr(self, key, value) else: self.LOG.info( "Skipping parsing of file ldap_config.ini as it has no 'ldap' section." )
class SncConfig(object): def __init__(self): self.config = RawConfigParser(allow_no_value=False) try: if ENVB_PATH in os.environ: self.config_file_path = os.environ[ ENVB_PATH] + os.sep + ENVBUILDER_CONF if len(str( self.config_file_path).strip()) > len(ENVBUILDER_CONF): self.config.read(self.config_file_path) else: self.config.read(ENVBUILDER_CONF) else: self.config.read(ENVBUILDER_CONF) os.environ[ENVB_PATH] = os.getcwd() except: ColorPrint.err("Config file {0} not found".format(ENVBUILDER_CONF)) exit(1) def getstring(self, section, param_name): try: return self.config.get(section, param_name) except: ColorPrint.err( "Config file {0} or section not found".format(ENVBUILDER_CONF)) exit(1) def getboolean(self, section, param_name): try: return self.config.getboolean(section, param_name) except: ColorPrint.err( "Config file {0} or section not found".format(ENVBUILDER_CONF)) exit(1) def getint(self, section, param_name): try: return self.config.getint(section, param_name) except: ColorPrint.err( "Config file {0} or section not found".format(ENVBUILDER_CONF)) exit(1) def getlist(self, section, param_name): try: cfg_list = self.config.get(section, param_name) return cfg_list.split(",") except: ColorPrint.err( "Config file {0} or section not found".format(ENVBUILDER_CONF)) exit(1) def getsection(self, section_name): try: return self.config.items(section_name) except: ColorPrint.err( "Config file {0} or section not found".format(ENVBUILDER_CONF)) exit(1)
def getint(self, section, option, default=None): val = default try: val = RawConfigParser.getint(self, section, option) except NoOptionError, e: # NOTE: None cannot be the default. if default is None: raise
def __init__(self): config = RawConfigParser() config.read('../config.ini') self.bot_name = (config.get('main', 'email')).lower() self.db_type = config.getint('main', 'db_type') conn_string = "host='5.9.51.242' port='5432' dbname='db_botnet' user='******' password='******'" self.con = psycopg2.connect(conn_string) self.cur = self.con.cursor(cursor_factory=psycopg2.extras.DictCursor)
def getint(self, section, option, *args): if len(args) > 0: try: return RawConfigParser.getint(self, section, option) except (NoSectionError, NoOptionError): return args[0] else: return RawConfigParser.get(self, section, option)
def __init__(self): try: Config = RawConfigParser() Config.read("config.cfg") self.socket = socket() self.socket.bind((Config.get("listen", "ip"), Config.getint("listen", "port"))) self.socket.listen(Config.getint("listen", "limit")) while True: client, address = self.socket.accept() start_new_thread(self.cache, (client, address)) print("CONNECT: " + address[0] + ":" + str(address[1])) except Exception: pass except KeyboardInterrupt: exit("Abort ...") finally: return None
def read_config(filename, section='kleenex'): """ This looks for [kleenex] in ``filename`` such as the following: [kleenex] db = sqlite:///coverage.db parent = origin/master discover = true report = true report_output = - record = true skip_missing = true max_distance = 4 test_missing = true max_revisions = 100 """ config = RawConfigParser({ 'db': 'sqlite:///coverage.db', 'parent': 'origin/master', 'discover': 'false', 'report': 'true', 'report_output': '-', 'record': 'false', 'skip_missing': 'true', 'max_distance': '4', 'test_missing': 'true', 'max_revisions': '100', }, dict_type=Config) config.read(filename) if not config.has_section(section): return config.defaults() return Config({ 'db': config.get(section, 'db'), 'parent': config.get(section, 'parent'), 'discover': config.getboolean(section, 'discover'), 'report': config.getboolean(section, 'report'), 'report_output': config.get(section, 'report_output'), 'record': config.getboolean(section, 'record'), 'skip_missing': config.getboolean(section, 'skip_missing'), 'max_distance': config.getint(section, 'max_distance'), 'test_missing': config.getboolean(section, 'test_missing'), 'max_revisions': config.getint(section, 'max_revisions'), })
class Config(object): """ Manage configuration - a simple wrapper around RawConfigParser. Upon initialization, the loaded file is updated with the default values. config.save() will save the current state. """ def __init__(self): self.filename = get_config_fn() try: self.parser = RawConfigParser(dict_type=OrderedDict) except TypeError: # Python versions < 2.6 don't support dict_type self.parser = RawConfigParser() f = StringIO(default_config) self.parser.readfp(f) self.parser.read(self.filename) self.save() def get(self, key, section='DreamPie'): return self.parser.get(section, key) def get_bool(self, key, section='DreamPie'): return self.parser.getboolean(section, key) def get_int(self, key, section='DreamPie'): return self.parser.getint(section, key) def set(self, key, value, section='DreamPie'): self.parser.set(section, key, value) def set_bool(self, key, value, section='DreamPie'): value_str = 'True' if value else 'False' self.set(key, value_str, section) def set_int(self, key, value, section='DreamPie'): if value != int(value): raise ValueError("Expected an int, got %r" % value) self.set(key, '%d' % value, section) def sections(self): return self.parser.sections() def has_section(self, section): return self.parser.has_section(section) def add_section(self, section): return self.parser.add_section(section) def remove_section(self, section): return self.parser.remove_section(section) def save(self): f = open(self.filename, 'w') self.parser.write(f) f.close()
def getint(self, section, option, default): value = default try: if RawConfigParser.has_section(self, section): if RawConfigParser.has_option(self, section, option): value = RawConfigParser.getint(self, section, option) except: value = default return value
def load(cls, filename): cfg = RawConfigParser(defaults=DEFAULTS) cfg.read(filename) return cls(cfg.get('postino', 'server'), cfg.getint('postino', 'port'), cfg.get('postino', 'login'), cfg.get('postino', 'password'), cfg.get('postino', 'sender'), cfg.get('postino', 'mode'), cfg.get('postino', 'to'), cfg.get('postino', 'cc'), cfg.get('postino', 'bcc'), cfg.get('postino', 'subject'))
def __init__(self, config_filename): self.config_filename = config_filename self.users = {} self.libraries = {} # ConfigParser with some default values config = RawConfigParser({ 'admin-name': 'Admin', # not really required so set default 'returns-days': '1234567', # can return books every day of week }) config.read(config_filename) usernames = config.get('libalert', 'users').split(',') for username in usernames: # Load all user settings username = username.strip() self.users[username] = { 'email': config.get(username, 'email'), 'number': config.get(username, 'number'), 'pin': config.get(username, 'pin'), 'library': config.get(username, 'library'), 'days-notice': config.getint(username, 'days-notice'), 'returns-days': parse_weekday_set(config.get(username, 'returns-days')) } # Load library details library = self.users[username]['library'] if library not in self.libraries: self.libraries[library] = { 'type': config.get(library, 'server-type'), 'url': config.get(library, 'server-url'), } self.admin_name = config.get('libalert', 'admin-name') self.admin_email = config.get('libalert', 'admin-email') self.smtp_server = config.get('libalert', 'smtp-server') self.smtp_email = config.get('libalert', 'smtp-email') self.smtp_password = config.get('libalert', 'smtp-password') self.debug_level = config.getint('libalert', 'debug-level')
def __init__(self, filepath): config = RawConfigParser() config.read(filepath) self.fp = filepath self.name = config.get('Task', 'name') self.description = config.get('Task', 'description') self.basic_url = config.get('Task', 'Basic_url') self.area = map(float, config.get('Task', 'Area').split(',')) self.max_z = config.getint('Task', 'maxZoom') self.min_z = config.getint('Task', 'minZoom') self.debug = config.getboolean('Debug', 'debugmode') self.debugTryTimes = config.getint('Debug', 'TryTimes') self.MAX_Threads = config.getint('Run', 'MAX_Threads') self.MAX_QUEUE = config.getint('Run', 'MAX_QUEUE') self.image_floder = config.get('File', 'ImageFloder') self.min_x = int(lonToTileX(self.area[0], self.min_z)) self.min_y = int(latToTileY(self.area[3], self.min_z)) self.max_x = int(lonToTileX(self.area[1], self.min_z)) self.max_y = int(latToTileY(self.area[2], self.min_z)) self.x = config.getint('Task-State', 'currentX') self.y = config.getint('Task-State', 'currentY') # Initialize if self.x == 0 and self.y == 0: self.x = self.min_x self.y = self.min_y # Breakpoint Resume elif self.x-self.min_x+(self.y-self.min_y)*(self.max_x-self.min_x)>3*self.MAX_QUEUE: if self.x - self.min_x > 3*self.MAX_QUEUE: self.x = self.x - 3*self.MAX_QUEUE else: self.x = self.max_x - (3*self.MAX_QUEUE - (self.x - self.min_x)) self.y = self.y - 1 else: self.x = self.min_x self.y = self.min_y print self.x, self.max_x print self.y, self.max_y print (self.max_x-self.x)*(self.max_y-self.y)
def MainProcess(): #--------------------------------- Initialization ------------------------------------ #Prepare Environment Variables: #CNF='/Users/xiaoming/Documents/workspace/myzabbixagent/src/vmagent.conf' Path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) CNF = Path + "/cnf/vmagent.conf" config = RawConfigParser() config.read(CNF) INTERVAL = config.getint('vmagent', 'interval') CACHE = Path + "/.cache/vmagent.cache" if not config.has_option( 'vmagent', 'cache') else config.get('vmagent', 'cache') LOGPATH = Path + "/log" if not config.has_option( 'vmagent', 'logpath') else config.get('vmagent', 'logpath') ZA = ZabbixAPI(url=config.get('zabbix', 'uri'), user=config.get('zabbix', 'user'), password=config.get('zabbix', 'password')) @TimeLimitbyProcess(config.getfloat('vmagent', 'timeout')) def GetInstances(config=config): return GetInstancesInfo(config) #Mark the start to log StartStr = "VM Daemon starts with PID %d." LogWrite(LOGPATH, status="Started", content=StartStr % os.getpid()) #One-off execution at start VmStatus = 1 while VmStatus: os.system('rm -f ' + CACHE) Last_Time = int(time.time()) try: DataList = GetInstances() print "First get info:", DataList #Mimic diagnostics API output #DataList=eval(getoutput('cat /Users/xiaoming/Documents/workspace/myzabbixagent/src/tmp/new1.txt')) except SyntaxError, e: LogWrite(LOGPATH, status="SyntaxError on input file", content=repr(e)) else: VmStatus = DataFormatCheck(DataList) print "Check result: ", VmStatus if VmStatus: print "Datacheck Error:", VmStatus continue if not VmStatus: Res_Initialized = Initialize(ZA, config) Data_to_Cache = EthReplace(ZA, config, DataExtract(DataList), Old=Res_Initialized["Mac_Eth"], Initialization=True) with open(CACHE, 'w') as f: f.write(json.dumps(Data_to_Cache)) CreateZabbixHost(ZA, config, DL=Data_to_Cache, Entire=True) finally:
def load_config(self, environ): """Load configuration options Options are read from a config file. Backwards compatibility: - if ConfigFile is not set, opts are loaded from http config - if ConfigFile is set, then the http config must not provide Koji options - In a future version we will load the default hub config regardless - all PythonOptions (except koji.web.ConfigFile) are now deprecated and support for them will disappear in a future version of Koji """ modpy_opts = environ.get('modpy.opts', {}) if 'modpy.opts' in environ: cf = modpy_opts.get('koji.web.ConfigFile', None) # to aid in the transition from PythonOptions to web.conf, we do # not check the config file by default, it must be configured else: cf = environ.get('koji.web.ConfigFile', '/etc/kojiweb/web.conf') if cf: if not os.path.isfile(cf): raise koji.GenericError, "Configuration missing: %s" % cf config = RawConfigParser() config.read(cf) else: #can only happen under mod_python self.logger.warn('Warning: configuring Koji via PythonOptions is deprecated. Use web.conf') opts = {} for name, dtype, default in self.cfgmap: if cf: key = ('web', name) if config.has_option(*key): if dtype == 'integer': opts[name] = config.getint(*key) elif dtype == 'boolean': opts[name] = config.getboolean(*key) else: opts[name] = config.get(*key) else: opts[name] = default else: if modpy_opts.get(name, None) is not None: if dtype == 'integer': opts[name] = int(modpy_opts.get(name)) elif dtype == 'boolean': opts[name] = modpy_opts.get(name).lower() in ('yes', 'on', 'true', '1') else: opts[name] = modpy_opts.get(name) else: opts[name] = default if 'modpy.conf' in environ: debug = environ['modpy.conf'].get('PythonDebug', '0').lower() opts['PythonDebug'] = (debug in ['yes', 'on', 'true', '1']) opts['Secret'] = koji.util.HiddenValue(opts['Secret']) self.options = opts return opts
def load_experiment_config(target_dir): from ConfigParser import RawConfigParser config_parser = RawConfigParser() config_parser.read(os.path.join(target_dir, "EXPERIMENT_CONFIG.cfg")) config = ExperimentConfig(config_parser) config.channel_thresholds = {} for channel in config.channels: config.channel_thresholds[channel] = config_parser.getint("config", "channel{}_threshold".format(channel)) config.channel_names[channel] = config_parser.get("config", "channel{}_name".format(channel)) return config
def load_config(path): c = RawConfigParser() c.read(path) d = {} d.update(c.items('servo')) d['pulse_port'] = c.getint('servo', 'pulse_port') d['pulse_ssl'] = c.getboolean('servo', 'pulse_ssl') return d
def load_state(self): fn = QtGui.QFileDialog.getOpenFileName(self, 'Load state') if fn == '': return cp = RawConfigParser() cp.read([fn]) sid.volume = cp.getint('main', 'volume') for v in sid.voices: sn = 'voice%d' % v.voicenum v.waveform = cp.getint(sn, 'waveform') v.pulse_width = cp.getfloat(sn, 'pulse_width') v.attack = cp.getint(sn, 'attack') v.decay = cp.getint(sn, 'decay') v.sustain = cp.getint(sn, 'sustain') v.release = cp.getint(sn, 'release') try: sn = cp.get(cp.get(sn, 'sources'), 'sources') self.load_sink_state(VoiceSink.POOL[v], cp, sn) except: pass
def run(config_file): log.info("Running with pid %i", os.getpid()) server = None listener = None handler = None while True: # Despite our caller already opening and reading this, we need to do it # here to make sure we pick up any changes during a reload. ini = RawConfigParser() ini.read(args["<config_file>"]) load_config(ini) credentials_file = ini.get("secrets", "credentials_file") credentials = json.load(open(credentials_file)) load_credentials(credentials) # TODO: test credentials at startup listen = ini.get("server", "listen") port = ini.getint("server", "port") bugzilla_client.configure( config["bugzilla_api"], config["bugzilla_username"], config["bugzilla_password"], ) processor.configure(config["concurrency"]) gevent.spawn(messenger) if not listener or (listen, port) != listener.getsockname(): if listener and server: log.info("Listener has changed, stopping old server") log.debug("Old address: %s", listener.getsockname()) log.debug("New address: %s", (listen, port)) server.stop() listener = socket.socket() listener.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) listener.bind((listen, port)) listener.listen(256) server = pywsgi.WSGIServer(listener, app, log=logger()) sighup_event = Event() h = gevent.signal(SIGHUP, lambda e: e.set(), sighup_event) if handler: handler.cancel() handler = h log.info("Running at %s", repr(server)) try: gevent.spawn(server.serve_forever) sighup_event.wait() except KeyboardInterrupt: break log.info("pid %i exited normally", os.getpid())
def __init__(self, conffile_path, conf_sec): super(APIFramework, self).__init__() conf = RawConfigParser(CONF_DEFAULTS) conf.read(conffile_path) self.listen_port = conf.getint(conf_sec, 'listen_port') #mysql self.db_host = conf.get(conf_sec, 'db_host') self.db_port = conf.getint(conf_sec, 'db_port') self.db_name = conf.get(conf_sec, 'db_name') self.db_user = conf.get(conf_sec, 'db_user') self.db_password = conf.get(conf_sec, 'db_password') db_max_connection = conf.getint(conf_sec, 'db_max_connections') db_stale_timeout = conf.getint(conf_sec, 'db_stale_timeout') #redis self.redis_server = conf.get(conf_sec, 'redis_server').split(',') self.redis_port = conf.getint(conf_sec, 'redis_port') self.redis_password = conf.get(conf_sec, 'redis_password') #debug self.debug = conf.getboolean(conf_sec, 'debug') #db/redis init self.db = db.get_MysqlConnection(self.db_host, self.db_port, self.db_user, self.db_password, self.db_name, db_max_connection, db_stale_timeout) self.redis_conn = db.get_RedisConnection(self.redis_server, self.redis_port, self.redis_password) #errors self.error_handler[404] = self.NotFoundError self.add_hook('before_request', self.before_request) self.add_hook('after_request', self.after_request) #install plugins self.install(ParseArgs()) #register handler self.loadHandlers(True) #install self handler if self.debug: Bottle.route(self, '/reloadhandlers', ['GET', 'POST'], self.loadHandlers) else: Bottle.route(self, '/reloadhandlers', 'POST', self.loadHandlers)