def __init__(self, path=None, with_defaults=False): RawConfigParser.__init__(self, dict_type=OrderedDict) self.path = path or os.environ.get(CONFIG_ENV, CONFIG_PATH) # Check if self.path is accessible abspath = os.path.abspath(self.path) if not os.path.exists(self.path): log.warning('Config file %s does not exist' % abspath) elif os.access(self.path, os.R_OK): if not os.access(self.path, os.W_OK): log.warning('Config file %s is not writable' % abspath) else: raise CLIError('Config file %s is inaccessible' % abspath, importance=3, details=['No read permissions for this file']) self._overrides = defaultdict(dict) if with_defaults: self._load_defaults() self.read(self.path) for section in self.sections(): r = self.cloud_name(section) if r: for k, v in self.items(section): self.set_cloud(r, k, v) self.remove_section(section)
def __init__(self, initialize=None): RawConfigParser.__init__(self) if initialize: for section, items in initialize.iteritems(): self.add_section(section) for key, value in items.iteritems(): self.set(section, key, value)
def __init__(self, filename): # let's read the file RawConfigParser.__init__(self) if isinstance(filename, basestring): self.read(filename) else: self.readfp(filename)
def __init__(self, path=None, with_defaults=False): RawConfigParser.__init__(self, dict_type=OrderedDict) self.path = path or os.environ.get(CONFIG_ENV, CONFIG_PATH) # Check if self.path is accessible abspath = os.path.abspath(self.path) if not os.path.exists(self.path): log.warning('Config file %s does not exist' % abspath) elif os.access(self.path, os.R_OK): if not os.access(self.path, os.W_OK): log.warning('Config file %s is not writable' % abspath) else: raise CLIError( 'Config file %s is inaccessible' % abspath, importance=3, details=['No read permissions for this file']) self._overrides = defaultdict(dict) if with_defaults: self._load_defaults() self.read(self.path) for section in self.sections(): r = self.cloud_name(section) if r: for k, v in self.items(section): self.set_cloud(r, k, v) self.remove_section(section)
def __init__(self, path, section='DEFAULT'): self.path = path RawConfigParser.__init__(self) # Old-style class if self.read(path): self._config = dict(self.items(section)) else: raise IOError('Failed to parse config file %s' % path)
def __init__(self, path=None): RawConfigParser.__init__(self) if path: self.location = path else: config_home = glib.get_user_config_dir() config_home = os.path.join(config_home, 'feattool') if not os.path.exists(config_home): os.makedirs(config_home) self.location = os.path.join(config_home, 'settings.ini') if not os.path.exists(self.location): open(self.location, "w").close() self._dirty = False self._saving = False try: self.read(self.location) except: pass #Save settings every 30 secs glib.timeout_add_seconds(30, self._timeout_save)
def __init__(self, filename=None, encoding="gbk", get_unicode=False, compact=False): RawConfigParser.__init__(self, dict_type=OrderedDictCaseInsensitive) self._encoding = encoding self._get_unicode = get_unicode self._compact = compact if filename: self.load(filename)
def __init__(self): ConfigParser.__init__(self) s = 'database' items = [ ['dbhost', 'localhost'], ['dbname', 'konsultant'], ['dbuser', os.environ['USER']], ['dbpass', ''], ['dbport', '5432'] ] self.add_section(s) self._additems(s, items) s = 'pgpool' items = [ ['usepgpool', 'false'], ['port', '5434'], ['command', '/usr/sbin/pgpool'], ['num_init_children', '32'], ['max_pool', '4'], ['connection_life_time', '0'] ] self.add_section(s) self._additems(s, items) s = 'client-gui' items = [ ['mainwinsize', '500, 400'], ['contactdlgsize', '200, 300'], ['locationdlgsize', '200, 400'] ] self.add_section(s) self._additems(s, items)
def __init__(self, path, fname=None, tzinfo=None): """ Read the description of the experiment timeline. :param path: a path to either the experiment timeline file or a directory containing experiment timeline file of either ``fname`` or `'config.txt'` or `'config*.(txt|ini)'` name (matching in that order). :type path: basestring :param fname: name of the experiment timeline file in ``path`` directory :type fname: basestring or None :param tzinfo: default timezone :type tzinfo: :py:class:`datetime.tzinfo` """ self.tzinfo = tzinfo RawConfigParser.__init__(self) if fname is None: if os.path.isfile(path): self.path = path elif os.path.isfile(os.path.join(path, 'config.txt')): self.path = os.path.join(path, 'config.txt') else: self.path = filter(lambda x: x.startswith('config') \ and (x.endswith('.txt') or x.endswith('.ini')), os.listdir(path))[0] else: self.path = os.path.join(path, fname) self.read(self.path)
def __init__(self, location=None, default_location=None): """ Sets up the settings manager. Expects a location to a file where settings will be stored. :param location: the location to save the settings to, settings will never be stored if this is None :type location: str or None :param default_location: the default location to initialize settings from """ RawConfigParser.__init__(self) self.location = location self._saving = False self._dirty = False if default_location is not None: try: self.read(default_location) except: pass if location is not None: try: self.read(self.location) or \ self.read(self.location + ".new") or \ self.read(self.location + ".old") except: pass if self.get_option('settings/version', 0) is None: self.set_option('settings/version', self.__version__)
def __init__(self, filename=None): """ Reads a configuration file and checks that the file contains all required information. If filename is None, an OntoConfig object will be created that returns only default values. """ # Call the superclass constructor. RawConfigParser.__init__(self) if filename is not None: # Call the superclass read() method. filesread = RawConfigParser.read(self, filename) if len(filesread) == 0: raise IOError('The configuration file, ' + filename + ', could not be opened.') self.confdir = os.path.dirname( os.path.abspath(os.path.realpath( os.path.expanduser(filename)))) else: # Use the current working directory as the configuration directory. self.confdir = os.path.dirname( os.path.abspath( os.path.realpath(os.path.expanduser(os.getcwd())))) self.conffile = filename
def __init__(self, configuration_file): RawConfigParser.__init__(self) f = codecs.open(configuration_file, 'r', encoding='utf-8') self.readfp(f) f.close() ''' set defaults ''' self.hostname = 'localhost' self.port = 1883 self.username = None self.password = None self.clientid = SCRIPTNAME self.lwt = 'clients/%s' % SCRIPTNAME self.skipretained = False self.cleansession = False self.protocol = 3 # db connection self.db_host = 'localhost' self.db_port = 3306 self.db_user = None self.db_pass = None self.db_name = 'nnpark' self.logformat = '%(asctime)-15s %(levelname)-5s [%(module)s] %(message)s' self.logfile = LOGFILE self.loglevel = 'DEBUG' self.functions = None self.num_workers = 1 self.directory = '.' self.ca_certs = None self.tls_version = None self.certfile = None self.keyfile = None self.tls_insecure = False self.tls = False self.api_topic = 'NNPARK' self.__dict__.update(self.config('defaults')) if HAVE_TLS == False: sys.exit(2) if self.ca_certs is not None: self.tls = True if self.tls_version is not None: if self.tls_version == 'tlsv1_2': self.tls_version = ssl.PROTOCOL_TLSv1_2 if self.tls_version == 'tlsv1_1': self.tls_version = ssl.PROTOCOL_TLSv1_1 if self.tls_version == 'tlsv1': self.tls_version = ssl.PROTOCOL_TLSv1 if self.tls_version == 'sslv3': self.tls_version = ssl.PROTOCOL_SSLv3 self.loglevelnumber = self.level2number(self.loglevel)
def init(self, args): """Given a list of conf option flags and values, update the Conf object and return a new list of args pruned of those used. "--" stops processing (and is not returned in args list). """ RawConfigParser.__init__(self) self.optionxform = lambda option: option args = args[:] while args: arg = args.pop(0) if arg == "-c" and args: try: section, rest = args.pop(0).split(":", 1) option, value = rest.split("=", 1) self.set2(section, option, value) except: raise Exception() elif arg == "-f" and args: try: self.read(args.pop(0)) except: raise Exception() elif arg == "--": break return args
def __init__(self): RawConfigParser.__init__(self, defaults=self.CONFIG_DEFAULTS) self.add_section('PyHesiodFS') if sys.platform in self.CONFIG_FILES: self.read(self.CONFIG_FILES[sys.platform]) else: self.read(self.CONFIG_FILES['_DEFAULT'])
def __init__(self, config_file, config_type=None): """ Init a fits_reduce config instance. Parameters ---------- config_file : string Path to the config file config_type : string Means which script is calling this object. See Also -------- ConfigParser.RawConfigParser """ RawConfigParser.__init__(self) # Permitted units for the images self._permitted_image_units = ['adu', 'electron', 'photon', '1', ''] # Check if file exists if not os.path.exists(config_file): raise IOError('File %s does not exists.' % config_file) # Load configfile self.read(config_file) if config_type == 'reducer': self.ret = self._load_reducer_vars() else: print 'Error! Invalid config_type %s.' % config_type
def __init__(self, conn, table, section, mainfield=None, mainvalue=None, option='name', value='value'): self.conn = conn self.cursor = StatementCursor(self.conn) self.cursor.set_table(table) self._secfield = section bothnone = mainfield is None and mainvalue is None bothset = mainfield and mainvalue if not bothnone and not bothset: raise Error, 'both mainfield and mainvalue need to be set/unset' self._mainclause = None if bothset: self._mainclause = Eq(mainfield, mainvalue) self._fields = [self._secfield, option, value] RawConfigParser.__init__(self) for row in self.cursor.select(fields=self._fields, clause=self._mainclause): if row[0] not in self.sections(): self.add_section(row[0]) self.set(*row)
def __init__(self, env): """ Init method that will also read and write the configuration file. No further interaction is necessary. """ self.env = env # XXX: I do not know how to use super here because RawConfigParser does # not inherit from 'object'. RawConfigParser.__init__(self) # Dictionary to contain the optional comments. self.comments = {} self.config_file = self.env.config_file # Check if the config file exists. Otherwise give a message, create the # file and exits. if not os.path.exists(self.config_file): exists = False else: exists = True self.getConfiguration() if not exists: msg = ( "No config file exists. A default one has been created at %s. Please edit it and restart the application." % self.config_file ) print msg sys.exit()
def __init__(self, location, default_location=None, is_system_theme=False): RawConfigParser.__init__(self) self.is_system_theme = is_system_theme if default_location is None: default_location = get_config_path("default_theme.ini") try: self.read(default_location) except: pass try: self.read(location) except: pass self.location = location if default_location is None: default_location = get_config_path("default_theme.ini") try: self.read(default_location) except: pass try: self.read(location) except: pass self.location = location
def __init__(self, filename, name): RawConfigParser.__init__(self) self.filename = filename self.name = name if not os.path.isfile(filename): raise IOError("File for %s with name '%s' not found." % (name, filename)) self.read(filename)
def __init__(self, *args, **kwargs): RawConfigParser.__init__(self, *args, **kwargs) if not self.has_section('regrowl.server'): self.add_section('regrowl.server') self.get = self._wrap_default(self.get) self.getint = self._wrap_default(self.getint) self.getboolean = self._wrap_default(self.getboolean)
def __init__(self, path=None): RawConfigParser.__init__(self) if not path: path = "~/.toolch_preferences" self.fn = os.path.expanduser(path) self.read(self.fn)
def __init__(self, filename = "config"): """ Constructor """ RawConfigParser.__init__(self, self._defaults) self.res_dir = None self.locale_dir = None self.updated = False self.set_filename(filename) self.load()
def __init__(self, path_to_fname): if os.path.isfile(path_to_fname): self.config_path = path_to_fname else: raise Exception("Could not find experiment config file %s for modular experiments", path_to_fname) RawConfigParser.__init__(self) self.read(path_to_fname)
def parse_config_files(self, filenames=None): if filenames is None: filenames = self.find_config_files() log.debug("Distribution.parse_config_files():") parser = RawConfigParser() for filename in filenames: log.debug(" reading %s" % filename) parser.read(filename) if os.path.split(filename)[-1] == 'setup.cfg': self._read_metadata(parser) for section in parser.sections(): options = parser.options(section) opt_dict = self.dist.get_option_dict(section) for opt in options: if opt != '__name__': val = parser.get(section, opt) opt = opt.replace('-', '_') # XXX this is not used ... # Hooks use a suffix system to prevent being overriden # by a config file processed later (i.e. a hook set in # the user config file cannot be replaced by a hook # set in a project config file, unless they have the # same suffix). if (opt.startswith("pre_hook.") or opt.startswith("post_hook.")): hook_type, alias = opt.split(".") hook_dict = opt_dict.setdefault(hook_type, (filename, {}))[1] hook_dict[alias] = val else: opt_dict[opt] = (filename, val) # Make the RawConfigParser forget everything (so we retain # the original filenames that options come from) parser.__init__() # If there was a "global" section in the config file, use it # to set Distribution options. if 'global' in self.dist.command_options: for (opt, (src, val)) in self.dist.command_options['global'].items(): alias = self.dist.negative_opt.get(opt) try: if alias: setattr(self.dist, alias, not strtobool(val)) elif opt in ('verbose', 'dry_run'): # ugh! setattr(self.dist, opt, strtobool(val)) else: setattr(self.dist, opt, val) except ValueError, msg: raise DistutilsOptionError(msg)
def __init__(self, defaults=None): RawConfigParser.__init__(self, defaults) # Protect global_options (may be temporary) self.__global_options = {} # OpenSLL by default uses spaces in section names, so that the # ca section would be represented as [ ca ] in the config file self.__spaces_in_section_names = True
def __init__(self, url): ''' Initialize our object :param version: a string like 4.3.1 ''' RawConfigParser.__init__(self) self._url = url self.urlfp = urlopen(self._url) self.readfp(self.urlfp)
def __init__(self, configuration_file): RawConfigParser.__init__(self) try: f = codecs.open(configuration_file, 'r', encoding='utf-8') self.readfp(f) f.close() except: print "Cannot open configuration file ", configuration_file sys.exit(2)
def __init__(self, defaults=None, dict_type=_default_dict, allow_no_value=False): RawConfigParser.__init__(self, defaults=defaults, dict_type=dict_type, allow_no_value=allow_no_value) self._comments = self._dict()
def __init__(self): RawConfigParser.__init__(self) # Set defaults self.add_section('ldap') self.add_section('presence') self.set('ldap', 'server', 'ldap://pan.suse.de') self.set('ldap', 'base', 'o=Novell') self.set('presence', 'servers', 'present.suse.de,bolzano.suse.de/nosend')
def __init__(self, conn, profile): self.conn = conn self.profile = profile self.env = ProfileEnvironment(self.conn) self.env.set_profile(self.profile) RawConfigParser.__init__(self) for row in self.env.get_rows(): if row.trait not in self.sections(): self.add_trait(row.trait) self.set(row.trait, row.name, row.value)
def __init__(self, fileName): RawConfigParser.__init__(self) self.fileName = fileName self.optionxform = str if os.path.exists(fileName): fp = open(fileName, 'r') try: self.readfp(fp) finally: fp.close()
def __init__(self, project_file_rel_path=None, resources_path=None, type_declarations=None): RawConfigParser.__init__(self) self.project_file_rel_path = project_file_rel_path self.resources_path = resources_path self.set_type_declarations(type_declarations) self.set_defaults() self.read_project_config_file() self.modify_defaults() self.print_debug(self)
def __init__(self): RawConfigParser.__init__(self) # Set defaults self.add_section('ldap') self.add_section('presence') self.set('ldap', 'server', 'ldap://pan.suse.de') self.set('ldap', 'base', 'o=Novell') self.set( 'presence', 'servers', 'present.suse.de,bolzano.suse.de/nosend' )
def __init__(self, filename=_defaultconf): RawConfigParser.__init__(self) fobj = open(self._defaultconf) self.readfp(fobj) try: fobj = open(filename, 'r') self.readfp(fobj) except IOError: self.write(open("useroptions.conf", 'w'))
def __init__(self): ConfigParser.__init__(self) self.config_file = abspath(join(dirname(dirname(__file__)), "tranny.ini")) try: loaded = self.read([self.config_file]) if not len(loaded) == 1: raise ConfigError("Failed to load configuration") except IOError: raise ConfigError("No config file found: {}".format(self.config_file))
def __init__(self, defaults): self._current_values = {} self._cache = {} RawConfigParser.__init__(self) for section in defaults: items = section[1:] section = section[0] self.add_section(section) for key, value in items: self.set(section, key, value)
def __init__(self, filename): if (os.path.exists(filename)): with open(filename) as f: content = f.read() RawConfigParser.__init__(self, allow_no_value=True) self.readfp(io.BytesIO(content)) else: print "File not found: " + filename sys.exit()
def __init__(self, file=None, register=False, **args): RawConfigParser.__init__(self, **args) self.logger = logging.getLogger(__name__) self.daemon = None if(file is None): self.read(["/etc/MaxiNet.cfg", os.path.expanduser("~/.MaxiNet.cfg"), "MaxiNet.cfg"]) self.set_loglevel() if(register): self.register()
def __init__(self, *args, **kwargs): RawConfigParser.__init__(self, *args, **kwargs) for section in DEFAULTS: self.add_section(section) for (option, value) in DEFAULTS[section].items(): self.set(section, option, value) self.get = self._wrap_default(self.get) self.getint = self._wrap_default(self.getint) self.getboolean = self._wrap_default(self.getboolean)
def __init__(self, defaults, filename): RawConfigParser.__init__(self) self.defaults = defaults try: open(filename) self.read(filename) except: for section in DEFAULTS: self.add_section(section[0]) for key, val in section[1].iteritems(): self.set(section[0], key, val)
def __init__(self, file=None, register=False, **args): RawConfigParser.__init__(self, **args) self.logger = logging.getLogger(__name__) self.daemon = None if (file is None): self.read([ "/etc/MaxiNet.cfg", os.path.expanduser("~/.MaxiNet.cfg"), "MaxiNet.cfg" ]) self.set_loglevel() if (register): self.register()
def __init__(self, path, fname=None): RawConfigParser.__init__(self) self.path = path if fname is None: if os.path.isfile(os.path.join(path, 'config.txt')): self.fname = 'config.txt' else: self.fname = filter( lambda x: x.startswith('config') and x.endswith('.txt'), os.listdir(path))[0] else: self.fname = fname self.read(os.path.join(path, self.fname))
def __init__(self, filename=None, encoding=None, get_unicode=False, compact=False): RawConfigParser.__init__(self, dict_type=OrderedDictCaseInsensitive) if encoding is None: encoding = SYS_ENCODING self._encoding = encoding self._get_unicode = get_unicode self._compact = compact if filename: self.load(filename)
def __init__(self): RawConfigParser.__init__(self, allow_no_value=True) self.environ = CecogEnvironment(version) self._registry = OrderedDict() self._current_section = None self._old_file_format = False self._section_registry = SectionRegistry() for section_name in self._section_registry.section_names(): self.add_section(section_name) section = self._section_registry.get_section(section_name) for trait_name in section.get_trait_names(): trait = section.get_trait(trait_name) self.set(section_name, trait_name, trait.default_value)
def __init__(self, repo_name=None): RawConfigParser.__init__(self) if repo_name is not None: assert isinstance(repo_name, str) self.__repo_name = repo_name d = dirname(abspath(__file__)) f = join_path(d, 'admin', 'cli.py') self.__python_evn_module_dir = d self.__python_evn_admin_cli_file_fullpath = f self.__load_defaults() self.__multiline_pattern = re.compile(r'([^\s].*?)([\s]+\\)?') self.__validate()
def __init__(self, section_registry): RawConfigParser.__init__(self, dict_type=OrderedDict, allow_no_value=True) self._registry = OrderedDict() self._current_section = None self._old_file_format = False self._section_registry = section_registry for section_name in section_registry.get_section_names(): self.add_section(section_name) section = section_registry.get_section(section_name) for trait_name in section.get_trait_names(): trait = section.get_trait(trait_name) self.set(section_name, trait_name, trait.default_value)
def __init__(self, fromfile=None, topdir=None): ''' fromfile can be a file-like object (anything with a .readline method) or a filename, or a list of filenames. topdir specifies the default topdir that any 'relpath' arguments are assumed to be relative to (see add_image, add_checksum, etc.) ''' RawConfigParser.__init__(self, allow_no_value=True) self._fullpath = dict() # save relpath -> filename mappings here if hasattr(fromfile, 'readline'): self.readfp(fromfile) elif fromfile is not None: self.read(fromfile) self.topdir = topdir
def __init__(self, path, debug=False, mark_whitespace="`'`"): RawConfigParser.__init__(self) self.config_file = path self.debug = debug self.mrk_ws = mark_whitespace if os.path.exists(path): sanitize_config_file(path) try: self.read(path) except ParsingError: self.write() try: self.read(path) except ParsingError, p: print "Could not start wicd: %s" % p.message sys.exit(1)
def __init__(self): RawConfigParser.__init__(self) self.__repo_path = None self._repo_name = None self._repo_admins = None self._admins = None d = dirname(abspath(__file__)) f = join_path(d, 'admin', 'cli.py') self.__python_evn_module_dir = d self.__python_evn_admin_cli_file_fullpath = f self.__load_defaults() self._default_sections_copy = copy.deepcopy(self._sections) self.__multiline_pattern = re.compile(r'([^\s].*?)([\s]+\\)?') self.__validate()
def __init__(self, path="~/.config/tranny"): ConfigParser.__init__(self) self.config_file = abspath( join(dirname(dirname(__file__)), "tranny.ini")) try: loaded = self.read([self.config_file]) if not len(loaded) == 1: raise ConfigError("Failed to load configuration") except IOError: raise ConfigError("No config file found: {}".format( self.config_file)) self.config_path = expanduser(path) self.cache_path = join(self.config_path, 'cache_path') self.cache_file = join(self.cache_path, "cache.dbm") self.configured = False
def __init__(self, configuration_file): RawConfigParser.__init__(self) self.read(configuration_file) self.wsdl = self.get('Mantis', 'wsdl') self.username = self.get('Mantis', 'username') self.password = self.get('Mantis', 'password') self.project_id = self.get('Mantis', 'default_mantis_project_id') self.issue_description = unicode(self.get( 'Mantis', 'issue_description'), 'UTF-8') self.note_description = unicode(self.get( 'Mantis', 'note_description'), 'UTF-8') self.category_name = unicode(self.get('Mantis', 'category_name'), 'UTF-8') self.sqlite_file = self.get('Mantis2nagios', 'sqlite_file') self.inotify_file = self.get('Mantis2nagios', 'inotify_file')