def get_config(config_dir, filename): """Parses <filename> from <config_dir> and returns configuration. <filename> is assumed to be in `ini` format, and is parsed by RawConfigParser (instead of ConfigParser or SafeConfigParser) to avoid accidental '%' interpolation when an option's value includes '%' character (such as password strings). Please see more details at: https://docs.python.org/2/library/configparser.html If "[include]" section exists in <filename> and the value of "FILE_NAME" option in this section is not empty, also read included file from <config_dir> directory. The final configuration will be a combination of these two files. For options that are specified in both <filename> and included file, values in <filename> will always take precedence. """ config = RawConfigParser() config.read(normpath(join(config_dir, filename))) # If "[include]" section exists, and its "FILE_NAME" option has a # non-empty value, parse the included file as secondary configuration. if config.has_section('include') and config.get('include', 'FILE_NAME'): included_filename = config.get('include', 'FILE_NAME') secondary_config = RawConfigParser() secondary_config.read(normpath(join(config_dir, included_filename))) for section in secondary_config.sections(): if not config.has_section(section): config.add_section(section) for option, value in secondary_config.items(section): if not config.has_option(section, option): config.set(section, option, value) return config
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 load_config(options): def read_section_config(section): for key in parser.options(section): if getattr(options, key) is None: setattr(options, key, parser.get(section, key)) configfile = get_config_path(options.configfile) if configfile is None: return False config = options.config parser = ConfigParser() parser.read(configfile) if config is not None: if not parser.has_section(config): return False if parser.has_section(DEFAULTS): read_section_config(DEFAULTS) if config is not None: read_section_config(config) return True
class ParamStore(object): def __init__(self, root_dir, file_name): if not os.path.isdir(root_dir): os.makedirs(root_dir) self._path = os.path.join(root_dir, file_name) self._dirty = False # open config file self._config = RawConfigParser() self._config.read(self._path) def __del__(self): self.flush() def flush(self): if not self._dirty: return self._dirty = False of = open(self._path, "w") self._config.write(of) of.close() def get(self, section, option, default=None): """Get a parameter value and return a string. If default is specified and section or option are not defined in the file, they are created and set to default, which is then the return value. """ if not self._config.has_option(section, option): if default is not None: self.set(section, option, default) return default return self._config.get(section, option) def get_datetime(self, section, option, default=None): result = self.get(section, option, default) if result: return safestrptime(result) return result def set(self, section, option, value): """Set option in section to string value.""" if not self._config.has_section(section): self._config.add_section(section) elif self._config.has_option(section, option) and self._config.get(section, option) == value: return self._config.set(section, option, value) self._dirty = True def unset(self, section, option): """Remove option from section.""" if not self._config.has_section(section): return if self._config.has_option(section, option): self._config.remove_option(section, option) self._dirty = True if not self._config.options(section): self._config.remove_section(section) self._dirty = True
def test_upgrade_pstate_files(self): """ Test whether the existing pstate files are correctly updated to 7.1. """ os.makedirs(os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR)) # Copy an old pstate file src_path = os.path.join(self.CONFIG_PATH, "download_pstate_70.state") shutil.copyfile(src_path, os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "download.state")) # Copy a corrupt pstate file src_path = os.path.join(self.CONFIG_PATH, "download_pstate_70_corrupt.state") corrupt_dest_path = os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "downloadcorrupt.state") shutil.copyfile(src_path, corrupt_dest_path) old_config = RawConfigParser() old_config.read(os.path.join(self.CONFIG_PATH, "tribler70.conf")) convert_config_to_tribler71(old_config, state_dir=self.state_dir) # Verify whether the section is correctly renamed download_config = RawConfigParser() download_config.read(os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "download.state")) self.assertTrue(download_config.has_section("download_defaults")) self.assertFalse(download_config.has_section("downloadconfig")) self.assertFalse(os.path.exists(corrupt_dest_path)) # Do the upgrade again, it should not fail convert_config_to_tribler71(old_config, state_dir=self.state_dir)
class Config(): """ Load and access the carbonate configuration. """ def __init__(self, config_file): self.config_file = config_file self.config = RawConfigParser() self.config.read(config_file) def clusters(self): """Return the clusters defined in the config file.""" return self.config.sections() def destinations(self, cluster='main'): """Return a list of destinations for a cluster.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) destinations = self.config.get(cluster, 'destinations') return destinations.replace(' ', '').split(',') def replication_factor(self, cluster='main'): """Return the replication factor for a cluster as an integer.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) return int(self.config.get(cluster, 'replication_factor')) def ssh_user(self, cluster='main'): """Return the ssh user for a cluster or current user if undefined.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) try: return self.config.get(cluster, 'ssh_user') except NoOptionError: return pwd.getpwuid(os.getuid()).pw_name def whisper_lock_writes(self, cluster='main'): """Lock whisper files during carbon-sync.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) try: return bool(self.config.get(cluster, 'whisper_lock_writes')) except NoOptionError: return False def hashing_type(self, cluster='main'): """Hashing type of cluster.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) hashing_type = 'carbon_ch' try: return self.config.get(cluster, 'hashing_type') except NoOptionError: return hashing_type
def update_from_config(self, *config_search_paths): parser = RawConfigParser() parser.read(config_search_paths) if not parser.has_section('build'): return self.source_directory = self._get_config(parser, 'source_directory', self.source_directory) self.output_directory = self._get_config(parser, 'output_directory', self.output_directory) self.out_zip = self._get_config(parser, 'output_zipfile', self.out_zip) self.kickers = self._get_config_list(parser, 'kickers', self.kickers) self.resource_filters = self._get_config_list(parser, 'resource_filters', self.resource_filters) self.exclude_stdlib = self._get_config(parser, 'exclude_stdlib', self.exclude_stdlib) extra_excludes = self._get_config_list(parser, 'exclude_modules', []) self.exclude_modules.extend(extra_excludes) if not parser.has_section('epoxy'): return self.epoxy_use_dict_config = self._get_epoxy_boolean( parser, 'use_dict_config', self.epoxy_use_dict_config) self.epoxy_config_to_fs = self._get_epoxy_boolean( parser, 'write_config_to_fs', self.epoxy_config_to_fs) self.epoxy_config_to_zipfile = self._get_epoxy_boolean( parser, 'write_config_to_zip', self.epoxy_config_to_zipfile) if self.epoxy_use_dict_config: self.exclude_modules.append("yaml")
def test_upgrade_pstate_files(self): """ Test whether the existing pstate files are correctly updated to 7.1. """ os.makedirs(os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR)) # Copy an old pstate file src_path = os.path.join(self.CONFIG_PATH, "download_pstate_70.state") shutil.copyfile( src_path, os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "download.state")) # Copy a corrupt pstate file src_path = os.path.join(self.CONFIG_PATH, "download_pstate_70_corrupt.state") corrupt_dest_path = os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "downloadcorrupt.state") shutil.copyfile(src_path, corrupt_dest_path) old_config = RawConfigParser() old_config.read(os.path.join(self.CONFIG_PATH, "tribler70.conf")) convert_config_to_tribler71(old_config, state_dir=self.state_dir) # Verify whether the section is correctly renamed download_config = RawConfigParser() download_config.read( os.path.join(self.state_dir, STATEDIR_DLPSTATE_DIR, "download.state")) self.assertTrue(download_config.has_section("download_defaults")) self.assertFalse(download_config.has_section("downloadconfig")) self.assertFalse(os.path.exists(corrupt_dest_path)) # Do the upgrade again, it should not fail convert_config_to_tribler71(old_config, state_dir=self.state_dir)
def get_config(defaults, section): dir_root = get_config_dir() if dir_root is None: return {} configdir = os.path.join(dir_root, '.bittorrent') if not os.path.isdir(configdir): try: os.mkdir(configdir, 0700) except: pass p = RawConfigParser() p.read(os.path.join(configdir, 'config')) values = {} if p.has_section(section): for name, value in p.items(section): if name in defaults: values[name] = value if p.has_section('common'): for name, value in p.items('common'): if name in defaults and name not in values: values[name] = value if defaults.get('data_dir') == '' and \ 'data_dir' not in values and os.path.isdir(configdir): datadir = os.path.join(configdir, 'data') values['data_dir'] = datadir parseargs.parse_options(defaults, values) return values
class Config(object): def __init__(self, buildout_dir): self.cfg_path = os.path.join(buildout_dir, '.mr.developer.cfg') self._config = RawConfigParser() self._config.optionxform = lambda s: s self._config.read(self.cfg_path) self.develop = {} self.buildout_args = [] self.rewrites = [] if self._config.has_section('develop'): for package, value in self._config.items('develop'): value = value.lower() if value == 'true': self.develop[package] = True elif value == 'false': self.develop[package] = False elif value == 'auto': self.develop[package] = 'auto' else: raise ValueError("Invalid value in 'develop' section of '%s'" % self.cfg_path) if self._config.has_option('buildout', 'args'): args = self._config.get('buildout', 'args').split("\n") for arg in args: arg = arg.strip() if arg.startswith("'") and arg.endswith("'"): arg = arg[1:-1].replace("\\'", "'") elif arg.startswith('"') and arg.endswith('"'): arg = arg[1:-1].replace('\\"', '"') self.buildout_args.append(arg) (self.buildout_options, self.buildout_settings, _) = \ parse_buildout_args(self.buildout_args[1:]) if self._config.has_option('mr.developer', 'rewrites'): for rewrite in self._config.get('mr.developer', 'rewrites').split('\n'): self.rewrites.append(rewrite.split()) def save(self): self._config.remove_section('develop') self._config.add_section('develop') for package in sorted(self.develop): state = self.develop[package] if state is 'auto': self._config.set('develop', package, 'auto') elif state is True: self._config.set('develop', package, 'true') elif state is False: self._config.set('develop', package, 'false') if not self._config.has_section('buildout'): self._config.add_section('buildout') options, settings, args = parse_buildout_args(self.buildout_args[1:]) # don't store the options when a command was in there if not len(args): self._config.set('buildout', 'args', "\n".join(repr(x) for x in self.buildout_args)) if not self._config.has_section('mr.developer'): self._config.add_section('mr.developer') self._config.set('mr.developer', 'rewrites', "\n".join(" ".join(x) for x in self.rewrites)) self._config.write(open(self.cfg_path, "w"))
class ConfigStore(object): def __init__(self, name): self.config = RawConfigParser() self.file_opts = {} if sys.version_info[0] >= 3: self.file_opts['encoding'] = 'utf-8' if hasattr(appdirs, 'user_config_dir'): data_dir = appdirs.user_config_dir('photini') else: data_dir = appdirs.user_data_dir('photini') if not os.path.isdir(data_dir): os.makedirs(data_dir, mode=0700) self.file_name = os.path.join(data_dir, '%s.ini' % name) if name == 'editor': for old_file_name in (os.path.expanduser('~/photini.ini'), os.path.join(data_dir, 'photini.ini')): if os.path.exists(old_file_name): self.config.read(old_file_name, **self.file_opts) self.save() os.unlink(old_file_name) self.config.read(self.file_name, **self.file_opts) self.timer = QtCore.QTimer() self.timer.setSingleShot(True) self.timer.setInterval(3000) self.timer.timeout.connect(self.save) self.has_section = self.config.has_section def get(self, section, option, default=None): if self.config.has_option(section, option): result = self.config.get(section, option) if sys.version_info[0] < 3: return result.decode('utf-8') return result if default is not None: self.set(section, option, default) return default def set(self, section, option, value): if not self.config.has_section(section): self.config.add_section(section) if (self.config.has_option(section, option) and self.config.get(section, option) == value): return if sys.version_info[0] < 3: value = value.encode('utf-8') self.config.set(section, option, value) self.timer.start() def remove_section(self, section): if not self.config.has_section(section): return for option in self.config.options(section): self.config.remove_option(section, option) self.config.remove_section(section) self.timer.start() def save(self): self.config.write(open(self.file_name, 'w', **self.file_opts)) os.chmod(self.file_name, 0600)
class Config(): """ Load and access the carbonate configuration. """ def __init__(self, config_file): self.config_file = config_file self.config = RawConfigParser() self.config.read(config_file) def clusters(self): """Return the clusters defined in the config file.""" return self.config.sections() def destinations(self, cluster='main'): """Return a list of destinations for a cluster.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) destinations = self.config.get(cluster, 'destinations') return destinations.replace(' ', '').split(',') def replication_factor(self, cluster='main'): """Return the replication factor for a cluster as an integer.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) return int(self.config.get(cluster, 'replication_factor')) def ssh_user(self, cluster='main'): """Return the ssh user for a cluster or current user if undefined.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) try: return self.config.get(cluster, 'ssh_user') except NoOptionError: return pwd.getpwuid(os.getuid()).pw_name def whisper_lock_writes(self, cluster='main'): """Lock whisper files during carbon-sync.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) try: return bool(self.config.get(cluster, 'whisper_lock_writes')) except NoOptionError: return False def hashing_type(self, cluster='main'): """Hashing type of cluster.""" if not self.config.has_section(cluster): raise SystemExit("Cluster '%s' not defined in %s" % (cluster, self.config_file)) hashing_type = 'carbon_ch' try: return self.config.get(cluster, 'hashing_type') except NoOptionError: return hashing_type
class AUSConfig(object): required_options = {"logging": ["logfile"], "database": ["dburi"]} # Originally, this was done with getattr(logging, level), but it seems bad # to look up, and possibly return, arbitrary keys from a config file so it # was replaced with this simple mapping. loglevels = {"DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "ERROR": logging.ERROR, "CRITICAL": logging.CRITICAL} def __init__(self, filename): self.cfg = RawConfigParser() self.cfg.read(filename) def validate(self): errors = [] for section, options in self.required_options.items(): if not self.cfg.has_section(section): errors.append("Missing section '%s'" % section) for opt in options: if not self.cfg.has_option(section, opt): errors.append("Missing option '%s' from section '%s'" % (opt, section)) return errors def getLogfile(self): return self.cfg.get("logging", "logfile") def getLogLevel(self): try: return self.loglevels[self.cfg.get("logging", "level")] # NoOptionError is raised when we can't find the level in the config. # KeyError is raised when we can't find it in the mapping. except (NoOptionError, KeyError): return logging.WARNING def getDburi(self): return self.cfg.get("database", "dburi") def getDomainWhitelist(self): # the config should have a format like this # domain_whitelist = download.mozilla.org:Firefox|Fennec|Thunderbird, ftp.mozilla.org:SystemAddons try: whitelist_config = dict() pref = self.cfg.get("site-specific", "domain_whitelist").split(", ") for domain_pref in pref: domain, products = domain_pref.split(":") products = products.split("|") whitelist_config[domain] = tuple(products) return whitelist_config except (NoSectionError, NoOptionError): return dict() def getCaches(self): caches = {} if self.cfg.has_section("caches"): for cache_name in self.cfg.options("caches"): size, timeout = self.cfg.get("caches", cache_name).split(",") caches[cache_name] = (int(size), int(timeout)) return caches
class Configuration(object): """To load and use configuration file.""" _config = None _location = None _section = "global" # Right now, this is the only section def __init__(self, location=None): """Initialize the Configuration class :type self: object :param location: The configuration file location. If None is used, then $HOME/.docc will be used. """ if location is None: self._location = os.path.expanduser("~/.docc") else: self._location = location self._config = RawConfigParser() self._config.read(self._location) def __getitem__(self, key): """Returns the value for the given key""" if not self._config.has_section(self._section): self._config.add_section(self._section) try: return self._config.get(self._section, key) except NoOptionError: raise KeyError( "%s is not a valid key in the configuration file" % key ) def __setitem__(self, key, value): """Set the key, value pair in the configuration and save to disk. Authorized keys are api_key, client_id """ # Create the default section if it is missing. if not self._config.has_section(self._section): self._config.add_section(self._section) self._config.set(self._section, key, value) # If the file exists, don't touch it as the user # may have decided on a different set of permissions set_permission = False location = self._location if os.path.exists(location): set_permission = True with open(location, "w") as f: self._config.write(f) if set_permission: os.chmod(location, 0600)
class Config(object): def __init__(self, filename): self.filename = filename self.config = None self.params_ask = ['twitter.username', 'twitter.password'] self.defaults = { 'twitter.timeline_date_format': '%Y.%m.%d %H:%M:%S', 'twitter.username': '', 'twitter.password': '', 'ui.separate_cached_entries': True } def __open_config(self): f = open(self.filename, 'w+') return f def read(self): self.config = RawConfigParser() if not self.config.read([self.filename]): f = self.__open_config() f.write('') f.close() self.read() def sync(self): f = self.__open_config() self.config.write(f) f.close() def __getitem__(self, item): section, name = item.split(".") if not all([section, name]): return None if self.config.has_section(section) and self.config.has_option(section, name): return self.config.get(section, name) else: if item in self.params_ask: if "password" in item: val = getpass("Please enter %s: " % name) else: val = raw_input("Please enter %s: " % name) if val: self[item] = val self.sync() return val if item in self.defaults: return self.defaults[item] return None def __setitem__(self, item, value): section, name = item.split(".") if not all([section, name]): return None if not self.config.has_section(section): self.config.add_section(section) self.config.set(section, name, value)
def create_initial_config(): """ create a new config file for CloudMailing. @return: """ config_filename = os.path.join(TARGET_PATH(), 'config', 'cloud-mailing.ini') from ConfigParser import RawConfigParser config = RawConfigParser() host_conf = local_settings.targets.get(env.host_string, {}) serial = host_conf.get('serial') if serial: config.add_section("ID") config.set('ID', 'SERIAL', serial) test_target = default_cm_config.get('test_target') if test_target: config.add_section("MAILING") config.set('MAILING', 'test_target_ip', test_target['ip']) config.set('MAILING', 'test_target_port', test_target['port']) remote_master_conf = host_conf.get('remote_master') if remote_master_conf: # satellite only if not config.has_section('MAILING'): config.add_section("MAILING") config.set('MAILING', 'master_ip', remote_master_conf['master_ip']) config.set('MAILING', 'master_port', remote_master_conf.get('master_port', 33620)) config.set('MAILING', 'shared_key', host_conf['shared_key']) else: # master + (eventually) satellite config.add_section("CM_MASTER") config.set( 'CM_MASTER', 'API_KEY', "".join([ random.choice( "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)") for i in range(50) ])) other_config = host_conf.get('config') if other_config: for section, content in other_config.items(): if not config.has_section(section): config.add_section(section) for key, value in content.items(): config.set(section, key, value) with tempfile.NamedTemporaryFile('w+t') as tmp: config.write(tmp) tmp.flush() run("mkdir -p %s/config" % TARGET_PATH()) put(tmp.name, config_filename) run("chown cm:cm %s" % config_filename)
class AUSConfig(object): required_options = {"logging": ["logfile"], "database": ["dburi"]} # Originally, this was done with getattr(logging, level), but it seems bad # to look up, and possibly return, arbitrary keys from a config file so it # was replaced with this simple mapping. loglevels = { "DEBUG": logging.DEBUG, "INFO": logging.INFO, "WARNING": logging.WARNING, "ERROR": logging.ERROR, "CRITICAL": logging.CRITICAL, } def __init__(self, filename): self.cfg = RawConfigParser() self.cfg.read(filename) def validate(self): errors = [] for section, options in self.required_options.items(): if not self.cfg.has_section(section): errors.append("Missing section '%s'" % section) for opt in options: if not self.cfg.has_option(section, opt): errors.append("Missing option '%s' from section '%s'" % (opt, section)) return errors def getLogfile(self): return self.cfg.get("logging", "logfile") def getLogLevel(self): try: return self.loglevels[self.cfg.get("logging", "level")] # NoOptionError is raised when we can't find the level in the config. # KeyError is raised when we can't find it in the mapping. except (NoOptionError, KeyError): return logging.WARNING def getDburi(self): return self.cfg.get("database", "dburi") def getDomainWhitelist(self): try: return tuple(a.strip() for a in self.cfg.get("site-specific", "domain_whitelist").split(",")) except (NoSectionError, NoOptionError): return tuple() def getCaches(self): caches = {} if self.cfg.has_section("caches"): for cache_name in self.cfg.options("caches"): size, timeout = self.cfg.get("caches", cache_name).split(",") caches[cache_name] = (int(size), int(timeout)) return caches
def commandRestore(self, parts, fromloc, overriderank): "/restore worldname number - Op\nRestore world to indicated number." if len(parts) < 2: self.client.sendServerMessage("Please specify at least a world ID!") else: world_id = parts[1].lower() world_dir = ("worlds/%s/" % world_id) if not self.client.isModPlus(): # ensure user has proper rank in the target world (the check to run this command only counts the world they're currently in) canRestore = False config = ConfigParser() config.read(world_dir+"world.meta") # this still has an issue: it won't pick up recent rank changes that haven't been flushed to the file yet. but it's good enough in geneal. if config.has_section("owner"): print config.get("owner", "owner") if config.get("owner", "owner").lower() == self.client.username.lower(): canRestore = True if config.has_section("ops"): for op in config.options("ops"): print op if op.lower() == self.client.username.lower(): canRestore = True if not canRestore: self.client.sendServerMessage("You are not allowed to restore that world!") return if len(parts) < 3: try: backups = os.listdir(world_dir+"backup/") except: self.client.sendServerMessage("Syntax: /restore worldname number") return backups.sort(lambda x, y: int(x) - int(y)) backup_number = str(int(backups[-1])) else: backup_number = parts[2] if not os.path.exists(world_dir+"backup/%s/" % backup_number): self.client.sendServerMessage("Backup %s does not exist." % backup_number) else: if not os.path.exists(world_dir+"blocks.gz.new"): shutil.copy(world_dir+"backup/%s/blocks.gz" % backup_number, world_dir) try: shutil.copy(world_dir+"backup/%s/world.meta" % backup_number, world_dir) os.remove(world_dir+"blocks.db") # remove blocktracker data since it's no longer valid except: pass else: reactor.callLater(1, self.commandRestore(self, parts, fromloc, overriderank)) default_name = self.client.factory.default_name self.client.factory.unloadWorld("worlds/%s" % world_id, world_id) self.client.sendServerMessage("%s has been restored to %s and booted." % (world_id, backup_number)) if world_id in self.client.factory.worlds: for client in self.client.factory.worlds[world_id].clients: client.changeToWorld(world_id)
def setup(): keys_defaults = [{'name': 'digitemp_path' , 'default': 'digitemp'}, {'name': 'digitemp_tty' , 'default': '/dev/ttyS0'}, {'name': 'mysql_host' , 'default': 'localhost'}, {'name': 'mysql_port' , 'default': '3306'}, {'name': 'mysql_user' , 'default': ''}, {'name': 'mysql_password' , 'default': ''}, {'name': 'mysql_database' , 'default': 'temperature'}] config = RawConfigParser() for x in keys_defaults: section, option = x['name'].split('_') config.has_section(section) or config.add_section(section) config.set(section, option, input_default(x['name'], x['default'])) print 'Writing config to temperature.conf' config.write(open(os.path.join(script_path, 'temperature.conf'), 'w')) print 'Writing base digitemprc' f = open('digitemprc', 'w') f.write( '''TTY %s READ_TIME 1000 LOG_TYPE 1 LOG_FORMAT "%%N %%R %%C" CNT_FORMAT " " HUM_FORMAT " " SENSORS 0 ''' % (config.get('digitemp', 'tty'))) f.close() print 'Initializing digitemprc sensor list' digitemp_cmd_base = config.get('digitemp', 'path') + ' -q -c ' + os.path.join(script_path, 'digitemprc') + ' ' get_program_output(digitemp_cmd_base + '-i') print 'Fetching list of sensors' sensors = [x.split(' ')[0] for x in get_program_output(digitemp_cmd_base + '-w').split('\n')[:-1]] db = MySQLdb.connect(host = config.get('mysql', 'host'), port = int(config.get('mysql', 'port')), user = config.get('mysql', 'user'), passwd = config.get('mysql', 'password'), db = config.get('mysql', 'database')) cursor = db.cursor() for sensor in sensors: desc = raw_input('Please enter a description for sensor %s: ' % sensor) cursor.execute("INSERT INTO `sensors` (`serial`, `description`) VALUES ('%s', '%s')" % (sensor, desc)) db.commit() del cursor, db print "Setup complete"
def parse_rc(file): defaults = {} rc = RawConfigParser() rc.optionxform = optionxform rc.read(file) if rc.has_section('core'): parser.set_defaults(**{ k: v for (k,v) in rc.items('core') }) if rc.has_section('tag'): mtag.subparser.set_defaults(**{ k: v for (k,v) in rc.items('tag') }) if rc.has_section('sort'): msort.subparser.set_defaults(**{ k: v for (k,v) in rc.items('sort') }) if rc.has_section('stat'): mstat.subparser.set_defaults(**{ k: v for (k,v) in rc.items('stat') }) return defaults
def loadMeta(self): "Loads the 'meta' - variables that change with the server (worlds, admins, etc.)" config = ConfigParser() config.read("data/server.meta") specs = ConfigParser() specs.read("data/spectators.meta") # Read in the worlds if config.has_section("worlds"): for name in config.options("worlds"): self.worlds[name] = None if name is "main": self.main_loaded = True else: self.worlds["main"] = None if not self.main_loaded: self.worlds["main"] = None # Read in the admins if config.has_section("admins"): for name in config.options("admins"): self.admins.add(name) # Read in the mods if config.has_section("mods"): for name in config.options("mods"): self.mods.add(name) if config.has_section("advbuilders"): for name in config.options("advbuilders"): self.advbuilders.add(name) # Read in the directors if config.has_section("directors"): for name in config.options("directors"): self.directors.add(name) if config.has_section("silenced"): for name in config.options("silenced"): self.silenced.add(name) # Read in the spectators if specs.has_section("spectators"): for name in specs.options("spectators"): self.spectators.add(name) # Read in the bans if config.has_section("banned"): for name in config.options("banned"): self.banned[name] = config.get("banned", name) # Read in the ipbans if config.has_section("ipbanned"): for ip in config.options("ipbanned"): self.ipbanned[ip] = config.get("ipbanned", ip) # Read in the ipspecs if specs.has_section("ipspecced"): for ip in specs.options("ipspecced"): self.ipbanned[ip] = config.get("ipspecced", ip)
def _readConfig(cls, filename): ''' Read the configuration file and return a pythonic configuration dict. ''' confParser = RawConfigParser( defaults={ # these keys can be commented out in the config file, # warning: the values are converted to strings 'user': None, 'pathRegexFilter': '', 'filenameRegexFilter': '', 'subPath': '', 'includes': '', 'macros': '', 'languages': '', 'metrics': '', 'settings': '', 'aggregateIssueLinks': '', 'shortBlockLines': 4 }) parsedFiles = confParser.read(filename) if not parsedFiles: msg = "Configuration file {} could not be read.".format(filename) raise Exception(msg) conf = { 'sina': {}, 'neteasy': {}, 'hanjie': {}, 'matching': {}, } # TODO: The 'configfie' entry is unused conf['consoleLog'] = confParser.getboolean('global', 'consoleLog') conf['debugMode'] = confParser.getboolean('global', 'debugMode') conf['encoding'] = confParser.get('global', 'encoding') conf['http_proxy'] = confParser.get('global', 'http_proxy') conf['configfile'] = os.path.abspath(filename) conf['basePath'] = os.path.abspath( convertOsPath(confParser.get('global', 'basePath'))) if confParser.has_section('sina'): conf['sina']['url'] = confParser.get('sina', 'url') conf['sina']['user'] = confParser.get('sina', 'user') conf['sina']['password'] = confParser.get('sina', 'password') if confParser.has_section('netease'): conf['netease']['url'] = confParser.get('netease', 'url') conf['netease']['user'] = confParser.get('netease', 'user') conf['netease']['password'] = confParser.get('netease', 'password') _convertDictUnicode(conf) return conf
class AUSConfig(object): required_options = {'logging': ['logfile'], 'database': ['dburi']} # Originally, this was done with getattr(logging, level), but it seems bad # to look up, and possibly return, arbitrary keys from a config file so it # was replaced with this simple mapping. loglevels = { 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL, } def __init__(self, filename): self.cfg = RawConfigParser() self.cfg.read(filename) def validate(self): errors = [] for section, options in self.required_options.items(): if not self.cfg.has_section(section): errors.append("Missing section '%s'" % section) for opt in options: if not self.cfg.has_option(section, opt): errors.append("Missing option '%s' from section '%s'" % (opt, section)) return errors def getLogfile(self): return self.cfg.get("logging", "logfile") def getLogLevel(self): try: return self.loglevels[self.cfg.get("logging", "level")] # NoOptionError is raised when we can't find the level in the config. # KeyError is raised when we can't find it in the mapping. except (NoOptionError, KeyError): return logging.WARNING def getDburi(self): return self.cfg.get('database', 'dburi') def getCefLogfile(self): if self.cfg.has_option('logging', 'cef_logfile'): return self.cfg.get('logging', 'cef_logfile') else: return "cef.log" def getSentryDsn(self): if self.cfg.has_option('logging', 'sentry_dsn'): return self.cfg.get('logging', 'sentry_dsn') else: return None def getDomainWhitelist(self): try: return tuple(a.strip() for a in self.cfg.get( 'site-specific', 'domain_whitelist').split(',')) except (NoSectionError, NoOptionError): return tuple()
def getFilenameInConfigFile(self, root_path, name): """Get filename field association in config file @root_path: Path where config file is stored @param name: Field name """ path = os.path.join(root_path, self.cfg_filename) # Config file doesn't exists if not os.path.exists(path): return None # If it exists parse it and get value fd = open(path, 'r') value = None try: config = RawConfigParser() config.readfp(fd) if config.has_section(self.cfg_filename_section) and \ config.has_option(self.cfg_filename_section, name): value = config.get(self.cfg_filename_section, name) finally: fd.close() return value
def handle_server_config_file(self, cnf_path, server, special_processing_reqs, desired_server_options): # We have a config reader so we can do # special per-server magic for setting up more # complex scenario-based testing (eg we use a certain datadir) config_reader = RawConfigParser() config_reader.read(cnf_path) # Do our checking for config-specific madness we need to do if config_reader and config_reader.has_section(server.name): # mark server for restart in case it hasn't yet # this method is a bit hackish - need better method later if '--restart' not in desired_server_options: desired_server_options.append('--restart') # We handle various scenarios server_config_data = config_reader.items(server.name) for cnf_option, data in server_config_data: if cnf_option == 'load-datadir': datadir_path = data request_key = 'datadir_requests' if request_key not in special_processing_reqs: special_processing_reqs[request_key] = [] special_processing_reqs[request_key].append( (datadir_path, server))
def setFilenameInConfigFile(self, root_path, name, filename): """Add new filename association in config file @root_path: Path where config file is stored @param name: Field name @param filename: Filename of value stored in field """ path = os.path.join(root_path, self.cfg_filename) # Update file config = RawConfigParser() if os.path.exists(path): # Read file fd = open(path, 'r') try: config.readfp(fd) finally: fd.close() # Create section if it doesn't exist if not config.has_section(self.cfg_filename_section): config.add_section(self.cfg_filename_section) config.set(self.cfg_filename_section, name, filename) fd = open(path, 'w') try: # Write file config.write(fd) finally: fd.close()
def parse_config(filename, dirs=None): if dirs: filenames = [os.path.join(d, filename) for d in dirs] else: filenames = [filename] config = RawConfigParser() n = config.read(filenames) if not len(n) >= 1: raise PkgNotFound("Could not find file(s) %s" % str(filenames)) # Parse meta and variables sections meta = parse_meta(config) vars = {} if config.has_section('variables'): for name, value in config.items("variables"): vars[name] = _escape_backslash(value) # Parse "normal" sections secs = [s for s in config.sections() if not s in ['meta', 'variables']] sections = {} requires = {} for s in secs: d = {} if config.has_option(s, "requires"): requires[s] = config.get(s, 'requires') for name, value in config.items(s): d[name] = value sections[s] = d return meta, vars, sections, requires
def setFilenameInConfigFile(self, root_path, name, filename): """Add new filename association in config file @root_path: Path where config file is stored @param name: Field name @param filename: Filename of value stored in field """ path = os.path.join(root_path, self.cfg_filename) # Update file config = RawConfigParser() if os.path.exists(path): # Read file fd = open(path, 'r') try: config.readfp(fd) finally: fd.close() # Create section if it doesn't exist if not config.has_section(self.cfg_filename_section): config.add_section(self.cfg_filename_section) config.set(self.cfg_filename_section, name, filename) fd = open(path, 'w') try: # Write file config.write(fd) finally: fd.close()
def load_configs(shutit): """Responsible for loading config files into ShutIt. Recurses down from configured shutit module paths. """ cfg = shutit.cfg # Get root default config. configs = [('defaults', StringIO.StringIO(_default_cnf))] # Add the shutit global host- and user-specific config file. configs.append(os.path.join(shutit.shutit_main_dir, 'configs/' + socket.gethostname() + '_' + cfg['host']['real_user'] + '.cnf')) configs.append(os.path.join(cfg['shutit_home'], 'config')) # Add the local build.cnf configs.append('configs/build.cnf') # Get passed-in config(s) for config_file_name in cfg['build']['extra_configs']: run_config_file = os.path.expanduser(config_file_name) if not os.path.isfile(run_config_file): print('Did not recognise ' + run_config_file + ' as a file - do you need to touch ' + run_config_file + '?') sys.exit() configs.append(run_config_file) # Image to use to start off. The script should be idempotent, so running it # on an already built image should be ok, and is advised to reduce diff space required. if cfg['build']['interactive'] >= 3 or cfg['action']['show_config']: msg = '' for c in configs: if type(c) is tuple: c = c[0] msg = msg + '\t\n' + c shutit.log('\t' + c) if cfg['build']['interactive'] >= 3: print textwrap.dedent("""\n""") + msg + textwrap.dedent(""" Looking at config files in the above order (even if they do not exist - you may want to create them). If you get a "Port already in use:" error, run: docker ps -a | grep -w <port> | awk '{print $1}' | xargs docker kill or sudo docker ps -a | grep -w <port> | awk '{print $1}' | xargs sudo docker kill """ + colour('31','[Hit return to continue]')) raw_input('') # Interpret any config overrides, write to a file and add them to the # list of configs to be interpreted if cfg['build']['config_overrides']: # We don't need layers, this is a temporary configparser override_cp = RawConfigParser() for o_sec, o_key, o_val in cfg['build']['config_overrides']: if not override_cp.has_section(o_sec): override_cp.add_section(o_sec) override_cp.set(o_sec, o_key, o_val) override_fd = StringIO.StringIO() override_cp.write(override_fd) override_fd.seek(0) configs.append(('overrides', override_fd)) cfg_parser = get_configs(shutit,configs) get_base_config(cfg, cfg_parser)
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_opener(): default_opener = urllib2.build_opener() if not exists(YUM_CONF): return default_opener config = RawConfigParser() config.read(YUM_CONF) if not config.has_section('main'): return default_opener if not config.has_option('main', 'proxy'): return default_opener proxy = {} url = config.get('main', 'proxy').strip() if not url: return default_opener http_proxy_handler = urllib2.ProxyHandler({'http': url, 'https': url}) # urllib2 can open HTTPS ressources through a proxy since python 2.6.3 # should be OK on Centos OS (Python 2.6.6) if config.has_option('main', 'proxy_username') and config.has_option( 'main', 'proxy_password'): username = config.get('main', 'proxy_username').strip() password = config.get('main', 'proxy_password').strip() password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password(None, url, username, password) proxy_auth_handler = urllib2.ProxyBasicAuthHandler(password_manager) return urllib2.build_opener(http_proxy_handler, proxy_auth_handler) return urllib2.build_opener(http_proxy_handler)
def parse_args(self, args=None, namespace=None): # config file detection config_bases = [os.path.expanduser('~/.')] try: from xdg.BaseDirectory import xdg_config_home; config_bases.append(xdg_config_home+'/') except: config_bases.append(os.environ.get('XDG_CONFIG_HOME') if os.environ.get('XDG_CONFIG_HOME', None) else os.path.expanduser('~/.config/')) config_file = '{}{}'.format(self.prog.lower(), self.kCONFIG_EXTENSION) possible_configs = [dir + config_file for dir in [item for base in config_bases for item in [base, '{}{}/'.format(base,self.prog)]]] possible_configs.append("{}/{}".format(os.path.dirname(os.path.realpath(__file__)), config_file)) # config parsing config = RawConfigParser() found_config = config.read(possible_configs) settings = dict(config.items(self.kCONFIG_SECTION)) if config.has_section(self.kCONFIG_SECTION) else {} for i, item in settings.items(): settings[i] = literal_eval(item) # fix values that might not be stored correctly (i.e bools) self.set_defaults(**settings) parsed_args = super(ArgConfParser, self).parse_args(args=args, namespace=namespace) # save config file if self.can_save and parsed_args.save_config: dict_args = vars(parsed_args) del dict_args[self.kKEY_SAVE] # don't want this one saved with open(found_config[0] if found_config else possible_configs[0] ,"w") as f: f.write(self.kCONFIG_HEADER+'\n'.join(['%s = \'%s\'' % (key, value) for (key, value) in dict_args.items()])) return parsed_args
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 __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 get_backend(self, backend_name): """ Get options of backend. :returns: a tuple with the module name and the module options dict :rtype: tuple """ config = RawConfigParser() config.read(self.confpath) if not config.has_section(backend_name): raise KeyError(u'Configured backend "%s" not found' % backend_name) items = dict(config.items(backend_name)) try: module_name = items.pop('_module') except KeyError: try: module_name = items.pop('_backend') self.edit_backend(backend_name, module_name, items) except KeyError: warning('Missing field "_module" for configured backend "%s"', backend_name) raise KeyError(u'Configured backend "%s" not found' % backend_name) return module_name, items
class Configuration: def __init__(self, configfile=None): print os.getenv("CONF") CONF_FILE = "%s/kst.conf" % os.getenv("CONF") self._configFile = CONF_FILE if not configfile else configfile self._genConf() def _setConfigFile(self, configFile=None): 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): return self._config.get(sect, opt) def get_section(self, section): if not self._config.has_section(section): return {} items = self._config.items(section) return dict(items)
def parse_config(filename, dirs=None): if dirs: filenames = [os.path.join(d, filename) for d in dirs] else: filenames = [filename] config = RawConfigParser() n = config.read(filenames) if not len(n) >= 1: raise PkgNotFound("Could not find file(s) %s" % str(filenames)) # Parse meta and variables sections meta = parse_meta(config) vars = {} if config.has_section('variables'): for name, value in config.items("variables"): vars[name] = _escape_backslash(value) # Parse "normal" sections secs = [s for s in config.sections() if not s in ['meta', 'variables']] sections = {} requires = {} for s in secs: d = {} if config.has_option(s, "requires"): requires[s] = config.get(s, 'requires') for name, value in config.items(s): d[name] = value sections[s] = d return meta, vars, sections, requires
def write_sts_token(self, profile, access_key_id, secret_access_key, session_token): """ Writes STS auth information to credentials file """ region = 'us-east-1' output = 'json' if not os.path.exists(self.creds_dir): os.makedirs(self.creds_dir) config = RawConfigParser() if os.path.isfile(self.creds_file): config.read(self.creds_file) if not config.has_section(profile): config.add_section(profile) config.set(profile, 'output', output) config.set(profile, 'region', region) config.set(profile, 'aws_access_key_id', access_key_id) config.set(profile, 'aws_secret_access_key', secret_access_key) config.set(profile, 'aws_session_token', session_token) with open(self.creds_file, 'w+') as configfile: config.write(configfile) print("Temporary credentials written to profile: %s" % profile) print("Invoke using: aws --profile %s <service> <command>" % profile)
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)
def install_mercurial_hook(): """ Installs the mercurial precommit hook by adding a hook to the hgrc file in the .hg directory of the repository. """ repo_dir = get_repo_dir() config_file = os.path.join(repo_dir, '.hg', 'hgrc') config_parser = RawConfigParser() config_parser.read(config_file) precommit_abs_file = os.path.join(repo_dir, 'scripts', 'codestyleprecommit.py') section = 'hooks' key = 'pretxncommit.precommit' value = 'python:%s:mercurial_hook' % precommit_abs_file if not config_parser.has_section(section): config_parser.add_section(section) config_parser.set(section, key, value) with open(config_file, 'w') as config: config_parser.write(config)
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 install_mercurial_hook(): """ Installs the mercurial precommit hook by adding a hook to the hgrc file in the .hg directory of the repository. """ repo_dir = get_repo_dir() config_file = os.path.join(repo_dir, '.hg', 'hgrc') config_parser = RawConfigParser() config_parser.read(config_file) precommit_abs_file = os.path.join(repo_dir, 'scripts', 'codestyleprecommit.py') section = 'hooks' key = 'pretxncommit.precommit' value = 'python:%s:mercurial_hook' % precommit_abs_file if not config_parser.has_section(section): config_parser.add_section(section) config_parser.set(section, key, value) with open(config_file, 'w') as config: config_parser.write(config)
def from_configfile(self, configfile): """ Initialize the authentication store from a "config"-style file. Auth "config" file is parsed with C{ConfigParser.RawConfigParser} and must contain an [auth] section which contains the usernames (keys) and passwords (values). Example auth file:: [auth] someuser = somepass anotheruser = anotherpass @param configfile: Path to config file or file-like object. @type configfile: C{any} @raise ValueError: If file could not be read or does not contain [auth] section. """ cfg = RawConfigParser() if hasattr(configfile, 'read'): cfg.readfp(configfile) else: filesread = cfg.read(configfile) if not filesread: raise ValueError('Could not parse auth file: %s' % configfile) if not cfg.has_section('auth'): raise ValueError('Config file contains no [auth] section.') self.store = dict(cfg.items('auth'))
def edit_profilevars(self): config = ProfileVariablesConfig(self.conn, self.current.profile) tmp, path = tempfile.mkstemp('variable', 'paella') tmp = file(path, 'w') config.write(tmp) tmp.close() os.system('$EDITOR %s' %path) tmp = file(path, 'r') newconfig = RawConfigParser() newconfig.readfp(tmp) tmp.close() os.remove(path) cursor = self.variables.env.cursor pclause = Eq('profile', self.current.profile) for trait in config.sections(): tclause = pclause & Eq('trait', trait) if not newconfig.has_section(trait): cursor.delete(clause=tclause) else: for name, value in newconfig.items(trait): nclause = tclause & Eq('name', name) if config.has_option(trait, name): if value != config.get(trait, name): cursor.update(data={'value' : value}, clause=nclause) else: idata = { 'profile' : self.current.profile, 'trait' : trait, 'name' : name, 'value' : value} cursor.insert(data=idata) if config.has_section(trait): for name, value in config.items(trait): if not newconfig.has_option(trait, name): cursor.delete(clause=tclause & Eq('name', name)) self.select_profile(self.current.profile)
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 commandFetch(self, user, fromloc, overriderank): "/fetch username - Op\nAliases: bring\nTeleports a user to be where you are" # Shift the locations right to make them into block coords rx = self.client.x >> 5 ry = self.client.y >> 5 rz = self.client.z >> 5 config = ConfigParser() config.read('config/data/fprot.meta') if config.has_section(user.username): self.client.sendServerMessage( "You can't fetch this person; they're Fetch Protected!") else: if user.world == self.client.world: user.teleportTo(rx, ry, rz) else: if self.client.isModPlus(): user.changeToWorld(self.client.world.id, position=(rx, ry, rz)) else: self.client.sendServerMessage( "%s cannot be fetched from '%s'" % (self.client.username, user.world.id)) return user.sendServerMessage("You have been fetched by %s" % self.client.username)
def from_config_file(self, config_file, allow_profile = False): """ Get the settings from a configuration file. :param config_file: Configuration file. :type config_file: str :param allow_profile: True to allow reading the profile name from the config file, False to forbid it. Global config files should allow setting a default profile, but profile config files should not, as it wouldn't make sense. """ parser = RawConfigParser() parser.read(config_file) if parser.has_section("golismero"): options = { k:v for k,v in parser.items("golismero") if v } if "profile" in options: if allow_profile: self.profile = options["profile"] self.profile_file = get_profile(self.profile) else: del options["profile"] for k in self._forbidden_: if k in options: del options[k] if options: self.from_dictionary(options)
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 ApplicationConfig(object): """A thin wrapper around ConfigParser that remembers what we read. The remembered settings can then be written out to a minimal config file when building the Elastic Beanstalk zipfile. """ def __init__(self): self.input = RawConfigParser() config_filename = os.environ.get("CONFIG", "production.ini") with open(config_filename) as f: self.input.readfp(f) self.output = RawConfigParser() def get(self, section, key): value = self.input.get(section, key) # remember that we needed this configuration value if (section.upper() != "DEFAULT" and not self.output.has_section(section)): self.output.add_section(section) self.output.set(section, key, value) return value def to_config(self): io = cStringIO.StringIO() self.output.write(io) return io.getvalue()
def parse_and_append( self, filename): try: parser = RawConfigParser() parser.read([filename]) if not parser.has_section(sect): return app_categories = parser.get(sect, 'Categories') if not app_categories: return if not any(category in self.PLAYER_CATEGORIES for category in app_categories.split(';')): return # Find out if we need it by comparing mime types app_mime = parser.get(sect, 'MimeType') for needed_type in self.mimetypes: if app_mime.find(needed_type+'/') != -1: app_name = parser.get(sect, 'Name') app_cmd = parser.get(sect, 'Exec') app_icon = parser.get(sect, 'Icon') if not self.__has_sep: self.add_separator() self.apps.append(UserApplication(app_name, app_cmd, app_mime, app_icon)) return except: return
class ApplicationConfig(object): """A thin wrapper around ConfigParser that remembers what we read. The remembered settings can then be written out to a minimal config file when building the Elastic Beanstalk zipfile. """ def __init__(self): self.input = RawConfigParser() with open("production.ini") as f: self.input.readfp(f) self.output = RawConfigParser() def get(self, section, key): value = self.input.get(section, key) # remember that we needed this configuration value if (section.upper() != "DEFAULT" and not self.output.has_section(section)): self.output.add_section(section) self.output.set(section, key, value) return value def to_config(self): io = cStringIO.StringIO() self.output.write(io) return io.getvalue()
def install_mercurial_hook(): """ Installs the mercurial precommit hook by adding a hook to the hgrc file in the .hg directory of the repository. """ repo_dir = get_repo_dir() config_file = os.path.join(repo_dir, ".hg", "hgrc") config_parser = RawConfigParser() config_parser.read(config_file) precommit_abs_file = os.path.join(repo_dir, "scripts", "codestyleprecommit.py") section = "hooks" key = "pretxncommit.precommit" value = "python:%s:mercurial_hook" % precommit_abs_file if not config_parser.has_section(section): config_parser.add_section(section) config_parser.set(section, key, value) with open(config_file, "w") as config: config_parser.write(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 from_config_file(self, config_file, allow_profile=False): """ Get the settings from a configuration file. :param config_file: Configuration file. :type config_file: str :param allow_profile: True to allow reading the profile name from the config file, False to forbid it. Global config files should allow setting a default profile, but profile config files should not, as it wouldn't make sense. """ parser = RawConfigParser() parser.read(config_file) if parser.has_section("golismero"): options = {k: v for k, v in parser.items("golismero") if v} if "profile" in options: if allow_profile: self.profile = options["profile"] self.profile_file = get_profile(self.profile) else: del options["profile"] for k in self._forbidden_: if k in options: del options[k] if options: self.from_dictionary(options)
def set(self, name, value): if self.custom_conf_file is None: raise GconfNotConfigurable() if not self._is_configurable(name): raise GconfNotConfigurable() if not self._is_valid_value(name, value): raise GconfInvalidValue() curr_val = self.gconf.get(name, None) if curr_val == value: return True cnf = RawConfigParser() with open(self.custom_conf_file) as f: cnf.readfp(f) if not cnf.has_section("vars"): cnf.add_section("vars") cnf.set("vars", name, value) with open(self.tmp_conf_file, "w") as fw: cnf.write(fw) os.rename(self.tmp_conf_file, self.custom_conf_file) self.reload() return True
def get_backend(self, backend_name): """ Get options of backend. :returns: a tuple with the module name and the module options dict :rtype: tuple """ config = RawConfigParser() config.read(self.confpath) if not config.has_section(backend_name): raise KeyError(u'Configured backend "%s" not found' % backend_name) items = dict(config.items(backend_name)) try: module_name = items.pop('_module') except KeyError: try: module_name = items.pop('_backend') self.edit_backend(backend_name, module_name, items) except KeyError: warning('Missing field "_module" for configured backend "%s"', backend_name) raise KeyError(u'Configured backend "%s" not found' % backend_name) return module_name, items
def handle_server_config_file( self , cnf_path , server , special_processing_reqs , desired_server_options ): # We have a config reader so we can do # special per-server magic for setting up more # complex scenario-based testing (eg we use a certain datadir) config_reader = RawConfigParser() config_reader.read(cnf_path) # Do our checking for config-specific madness we need to do if config_reader and config_reader.has_section(server.name): # mark server for restart in case it hasn't yet # this method is a bit hackish - need better method later if '--restart' not in desired_server_options: desired_server_options.append('--restart') # We handle various scenarios server_config_data = config_reader.items(server.name) for cnf_option, data in server_config_data: if cnf_option == 'load-datadir': datadir_path = data request_key = 'datadir_requests' if request_key not in special_processing_reqs: special_processing_reqs[request_key] = [] special_processing_reqs[request_key].append((datadir_path,server))
def getFilenameInConfigFile(self, root_path, name): """Get filename field association in config file @root_path: Path where config file is stored @param name: Field name """ path = os.path.join(root_path, self.cfg_filename) # Config file doesn't exists if not os.path.exists(path): return None # If it exists parse it and get value fd = open(path, 'r') value = None try: config = RawConfigParser() config.readfp(fd) if config.has_section(self.cfg_filename_section) and \ config.has_option(self.cfg_filename_section, name): value = config.get(self.cfg_filename_section, name) finally: fd.close() return value