def test_parse_config(self): fd, filename = tempfile.mkstemp() fp = os.fdopen(fd, 'w') try: cp = RawConfigParser() cp.add_section('sec') cp.set('sec', 'foo', 'foo') cp.set('sec', 'bar', '-1') cp.set('sec', 'baz', '-0.1') cp.set('sec', 'hum', 'yes') cp.set('sec', 'dum', 'no') cp.write(fp) fp.close() self.define_opt('sec', 'foo') self.define_opt('sec', 'bar', type=int) self.define_opt('sec', 'baz', type=float) self.define_opt('sec', 'hum', type=bool) self.define_opt('sec', 'dum', type=bool) self.parse_config(filename) self.verify_all_options() self.assertEqual(self.options.sec.foo, 'foo') self.assertEqual(self.options.sec.bar, -1) self.assertAlmostEqual(self.options.sec.baz, -0.1) self.assertEqual(self.options.sec.hum, True) self.assertEqual(self.options.sec.dum, False) finally: os.unlink(filename)
def _set_repository_id(self, path, id): config = RawConfigParser() config.read(os.path.join(path, 'config')) config.set('repository', 'id', hexlify(id).decode('ascii')) with open(os.path.join(path, 'config'), 'w') as fd: config.write(fd) return Repository(self.repository_path).id
def add_handler(filename, event, handler): config = RawConfigParser() config.read(filename) config['Handlers'][event] = handler with open(filename, 'w') as f: config.write(f)
def _set_repository_id(self, path, id): config = RawConfigParser() config.read(os.path.join(path, "config")) config.set("repository", "id", hexlify(id).decode("ascii")) with open(os.path.join(path, "config"), "w") as fd: config.write(fd) return Repository(self.repository_path).id
def get_host_port(args): """ Returns the hostname and port number """ import topicexplorer.config config = topicexplorer.config.read(args.config) # automatic port assignment def test_port(port): try: host = args.host or config.get("www", "host") if host == '0.0.0.0': host = 'localhost' try: s = socket.create_connection((host, port), 2) s.close() raise IOError("Socket connectable on port {0}".format(port)) except socket.error: pass return port except IOError: if not args.quiet: port = int_prompt( "Conflict on port {0}. Enter new port:".format(port)) return test_port(port) else: raise IOError( "Conflict on port {0}. Try running with -p to manually set new port.".format(port)) port = args.port or int(config.get('www', 'port').format(0)) port = test_port(port) # prompt to save if (int(config.get("www", "port").format(0))) != port: if not args.quiet and bool_prompt( "Change default baseport to {0}?".format(port), default=True): config.set("www", "port", text(port)) # create deep copy of configuration # see http://stackoverflow.com/a/24343297 config_string = StringIO() config.write(config_string) # skip DEFAULT section config_string.seek(0) idx = config_string.getvalue().index("[main]") config_string.seek(idx) # read deep copy new_config = ConfigParser() config.read_file(config_string) # write deep copy without DEFAULT section # this preserves DEFAULT for rest of program with open(args.config, 'w') as configfh: new_config.write(configfh) # hostname assignment host = args.host or config.get('www', 'host') return host, port
def mock_config(config_dir): data = dict( general=dict( conf_dir=config_dir, verbose=True, update_on_startup=False, ), mpd=dict( host='localhost', port=6600, ), lastfm=dict( scrobble_days=180, user='******', api_key='apikey', api_secret='secret', ), ) config = RawConfigParser() for section, options in data.items(): config.add_section(section) for key, value in options.items(): config.set(section, key, value) with NamedTemporaryFile(mode='w') as temp: config.write(temp) temp.flush() with patch('suggestive.config.CONFIG_PATHS', [temp.name]): return Config()
def write(self, filename, impl=FITS ,implementation=DATAIMPL): """ write configuration entries to a file. Parameters: ----------- filename: str Full path name: Save all configuration entries to this given filename impl: str , optional "FITS" -> use Fits format "INI" -> use windows style ini format """ if ( impl == self.FITS): self._write_fits(filename,implementation) #Write an .ini-format representation of the configuration state. elif ( impl == self.INI): config_parser = RawConfigParser() self._fill(config_parser) with open(filename, 'w') as config_file: config_parser.write(config_file) else: print("Format:",impl,'not allowed',file=sys.stderr)
def run(self): try: config_file = DEFAULT_CONF_FILE if not os.path.isfile(config_file): raise ValueError('Configuration file not found: {0}'.format(config_file)) config = RawConfigParser() config.read(config_file) if 'security' in config.sections(): return 'The configuration file is already migrated to the new version' config.add_section('security') config.add_section('database') for item in config.items('paths'): if item[0] == 'database_file': config.set('database', item[0], item[1]) else: config.set('security', item[0], item[1]) config.remove_section('paths') config.set('security', 'crl_file_url', 'None') config.set('logging', 'log_level', 'INFO') with open(config_file, 'w') as file: config.write(file) except Exception as exc: return exc return 'Configuration file migrated'
def save(self, filename, private=False): """ Save repository into a file (modules.list for example). :param filename: path to file to save repository. :type filename: str :param private: if enabled, save URL of repository. :type private: bool """ config = RawConfigParser() config.set(DEFAULTSECT, 'name', self.name) config.set(DEFAULTSECT, 'update', self.update) config.set(DEFAULTSECT, 'maintainer', self.maintainer) config.set(DEFAULTSECT, 'signed', int(self.signed)) config.set(DEFAULTSECT, 'key_update', self.key_update) if private: config.set(DEFAULTSECT, 'url', self.url) for module in self.modules.itervalues(): config.add_section(module.name) for key, value in module.dump(): config.set(module.name, key, to_unicode(value).encode('utf-8')) with open(filename, 'wb') as f: config.write(f)
class Options: def __init__(self, name, defaults): load_paths = list(reversed([os.path.join(directory, '%s.cfg' % name) for directory in load_config_paths(name)])) self.save_path = os.path.join(save_config_path(name), '%s.cfg' % name) self.config = RawConfigParser(defaults) self.paths = self.config.read(load_paths) self.section = name if self.config.has_section(name) else 'DEFAULT' def get(self, option): try: return self.config.get(self.section, option) except NoOptionError: return None def set(self, option, value): if value is not None: self.config.set(self.section, option, value) else: self.config.remove_option(self.section, option) defaults = self.config._defaults self.config._defaults = None with open(self.save_path, 'w') as save_file: self.config.write(save_file) self.config._defaults = defaults
def write(self, fp): parser = RawConfigParser() for section in self: parser.add_section(section) for key, value in self.items(section): parser.set(section, key, value) parser.write(fp)
def run_setup(self, config_file): print(textwrap.dedent("""\ Hi, it looks like it's the first time you're using pwm on this machine. Let's take a little moment to set things up before we begin.""")) db_uri = input('Which database do you want to use (default: local sqlite at ~/.pwm/db.sqlite) ').strip() or 'local' rc_dir = os.path.dirname(config_file) if db_uri == 'local': # normalize windows-style paths for sqlalchemy: rc_dir = rc_dir.replace('\\', '/') # Create the local database db_uri = 'sqlite:///%s/db.sqlite' % rc_dir if not '://' in db_uri: # Not a sqlalchemy-compatible connection string or https URI, assume it's a local path and make a sqlite # uri out of it db_uri = 'sqlite:///%s' % db_uri if not (db_uri.startswith('https:') or db_uri.startswith('http:')): # It's a local db, make sure our tables exist db = sa.create_engine(db_uri) Base.metadata.create_all(db) config_parser = RawConfigParser() config_parser.add_section('pwm') config_parser.set('pwm', 'database', db_uri) with open(config_file, 'w') as config_file_fh: config_parser.write(config_file_fh)
def write(self): """Write the config to the disk""" try: with self.file_name.open('w') as fp: RawConfigParser.write(self, fp) return True except IOError: return False
def save(self): """Save configuration to file.""" parser = RawConfigParser() parser.optionxform = str parser.read_dict({'Options': self._configs}) with open(os.path.join(app_config_dir, 'config'), 'w', encoding='utf-8') as f: parser.write(f)
def save_auth(self, username, password): """""" parser = RawConfigParser() parser.add_section("AUTH") parser.set("AUTH", "username", username) parser.set("AUTH", "password", password) filename = os.path.join(os.getenv("PINGUINO_USER_PATH"), "submit-auth") parser.write(open(filename, "w"))
def write(self): """Write the config to the disk""" try: fp = open(self.file_name, 'w') RawConfigParser.write(self, fp) fp.close() return True except IOError: return False
def incomplete_rc(tmpdir): rc_file = str(tmpdir / 'noperc') config = RawConfigParser() config['nope'] = {'foo': 'bar'} with open(rc_file, 'w', encoding='utf-8') as fh: config.write(fh) return rc_file
def write_settings(data): """Write dict to settings config. :param data: dict for write """ conf = RawConfigParser() conf.read_dict(data) with open(CONF_SETTINGS, 'w', encoding='utf-8') as file: conf.write(file)
def write_config(self, survey_dict=None, mosaic_dict=None, constants_dict=None, spectral_dict=None, spatial_dict=None): """ Writes all of the needed information to the config file called <mosaicname>.cfg """ if not os.path.isdir(SURVEY_CONFIG_DIR): os.makedirs(SURVEY_CONFIG_DIR) configfilename = survey_dict['survey'] + '_' + mosaic_dict['mosaic'] config = RawConfigParser() config.read(configfilename + '.cfg') if not config.has_section('survey'): config.add_section('survey') for variable, value in survey_dict.items(): config.set('survey', variable, value) self.logger.info('wrote common config to ' + configfilename + '.cfg.') if mosaic_dict: if config.has_section('mosaic'): self.logger.info("mosaic config exists, overwriting...") else: config.add_section('mosaic') for variable, value in mosaic_dict.items(): config.set('mosaic', variable, value) self.logger.info("wrote mosaic config to " + configfilename + ".cfg.") if constants_dict: if config.has_section('constants'): self.logger.info("constants config exists, overwriting...") else: config.add_section('constants') for variable, value in constants_dict.items(): config.set('constants', variable, value) self.logger.info("wrote constants config to " + configfilename + ".cfg.") if spectral_dict: if config.has_section('spectralSearch'): self.logger.info("spectralSearch config exists, overwriting...") else: config.add_section('spectralSearch') for variable, value in spectral_dict.items(): config.set('spectralSearch', variable, value) self.logger.info("wrote spectralSearch config to " + configfilename + ".cfg.") if spatial_dict: if config.has_section('spatialSearch'): self.logger.info("spatialSearch config exists, overwriting...") else: config.add_section('spatialSearch') for variable, value in spatial_dict.items(): config.set('spatialSearch', variable, value) self.logger.info("wrote spatialSearch config to " + configfilename + ".cfg.") with open(SURVEY_CONFIG_DIR + configfilename + '.cfg', 'w') as configfile: config.write(configfile)
def updateFile(self): c = RawConfigParser() c.read(self.WORK_FILE) for i in range(0, 40): c.set("pin" + str(i), "state", str(self.currState[i])) c.set("pin" + str(i), "value", str(self.currValue[i])) with open(self.WORK_FILE, 'w') as configfile: c.write(configfile)
def tmp_rc(tmpdir, tmp_templates_file): rc_file = str(tmpdir / 'userrc') config = RawConfigParser() config['github'] = {'username': '******', 'token': '1234'} config['templates'] = {'file': tmp_templates_file} with open(rc_file, 'w', encoding='utf-8') as fh: config.write(fh) return rc_file
def updateFile(self): c = RawConfigParser() c.read(self.WORK_FILE) for i in range(0,40): c.set("pin"+str(i),"state",str(self.currState[i])) c.set("pin"+str(i),"value",str(self.currValue[i])) with open(self.WORK_FILE, 'w') as configfile: c.write(configfile)
def handler_file(tmpdir): name = os.path.join(str(tmpdir), 'handler_file') config = RawConfigParser() config['Handlers'] = {} config['Handlers']['testevent'] = 'foo' with open(name, 'w') as f: config.write(f) return name
def openEqualizer(self): from configparser import RawConfigParser equa = Equalizer(self, Foo.readConfig('audio')) equa.equalize.connect(self.applyEqua) if equa.exec_(): parser = RawConfigParser() parser.read(os.path.dirname(os.path.realpath(__file__))+'/config') parser['audio']['settings']= str(equa.config) with open(os.path.dirname(os.path.realpath(__file__))+'/config', 'w') as configfile: parser.write(configfile)
def save(self, settings_dict): config = RawConfigParser(allow_no_value=True) config.read(self.filename) for section, d in settings_dict.items(): if not config.has_section(section): config.add_section(section) for option, value in d.items(): config.set(section, option, value) with atomic_write(self.filename, mode="w", overwrite=True) as f: config.write(f)
def setConfigContent(self, content): conf = RawConfigParser() conf.read(self.file_path) for section in content: section_items = content[section].items() for option, value in section_items: if conf.has_section(section) == False: conf.add_section(section) conf.set(section, option, value) conf.write(open(self.file_path, "w"))
def write(self, path): config = RawConfigParser() for section in self: config.add_section(section) for parameter in self[section]: config.set(section, parameter, self[section][parameter]) with open(path, 'w') as f: config.write(f)
def write_config(section, key, value): cfg = RawConfigParser() cfg.read('config/config.ini') if section not in cfg.sections(): cfg.add_section(section) cfg.set(section, key, value) with open('config/config.ini', 'w') as f: cfg.write(f)
class OktaAuthConfig(): """ Config helper class """ def __init__(self, logger): self.logger = logger self.config_path = os.path.expanduser('~') + '/.okta-aws' self._value = RawConfigParser() self._value.read(self.config_path) def base_url_for(self, okta_profile): """ Gets base URL from config """ if self._value.has_option(okta_profile, 'base-url'): base_url = self._value.get(okta_profile, 'base-url') self.logger.info("Authenticating to: %s" % base_url) else: base_url = self._value.get('default', 'base-url') self.logger.info("Using base-url from default profile %s" % base_url) return base_url def username_for(self, okta_profile): """ Gets username from config """ if self._value.has_option(okta_profile, 'username'): username = self._value.get(okta_profile, 'username') self.logger.info("Authenticating as: %s" % username) else: username = input('Enter username: '******'password'): password = self._value.get(okta_profile, 'password') else: password = getpass('Enter password: '******'factor'): factor = self._value.get(okta_profile, 'factor') self.logger.debug("Setting MFA factor to %s" % factor) return factor return None def save_chosen_role_for_profile(self, okta_profile, role_arn): """ Gets role from config """ if not self._value.has_section(okta_profile): self._value.add_section(okta_profile) base_url = self.base_url_for(okta_profile) self._value.set(okta_profile, 'base-url', base_url) self._value.set(okta_profile, 'role', role_arn) with open(self.config_path, 'w+') as configfile: self._value.write(configfile)
def _generate_config_file(self, config_file): conf = RawConfigParser() self._add_section_twitter(conf) self._add_section_key_bindings(conf) self._add_section_palette(conf) self._add_section_styles(conf) self._add_section_debug(conf) with open(config_file, 'w') as config: conf.write(config)
def save_raw_parser(self, content, filename): file_parser = RawConfigParser() count = 0 for block in content: count += 1 name_section = "Block-%d"%count file_parser.add_section(name_section) for key in block.keys(): file_parser.set(name_section, key, block[key]) file_parser.write(codecs.open(filename, "w", "utf-8"))
class GenerateConfig(object): def __init__(self): # self.cf = ConfigParser() self.cfw = RawConfigParser() self.cfr = ConfigParser() self.resources = {} self.log = {} self.init_resources() def init_resources(self): if os.path.exists(resource_path): f = open(resource_path, 'r') data = f.read() f.close() if len(data) > 0: self.resources = json.loads(data) def write_file(self): f = open(resource_log_path, 'w') f.write(json.dumps(self.log)) f.close() def set_cf(self, service, option, keyname): item = self.resources[service][option][keyname] self.cfw.set(service, option, item) def generate_resources_config_file(self): for service in self.resources.keys(): if service != 'resource': self.cfw.add_section(service) for option in self.resources[service]: if service == 'ecs_task_definitions': self.set_cf(service, option, 'taskDefinitionArns') elif service == 'eips': self.set_cf(service, option, 'PublicIp') elif service == 'volumes': self.set_cf(service, option, 'VolumeId') else: for key in self.resources[service][option].keys(): self.set_cf(service, option, key) f = open(resource_config_path, 'w') self.cfw.write(f) def generate_resources_log(self): self.cfr.read(resource_config_path) for section in self.cfr.sections(): self.log[section] = {} for option in self.cfr.options(section): self.log[section][option] = self.cfr.get(section, option) self.write_file() def main(self): self.generate_resources_config_file() self.generate_resources_log()
def save_raw_parser(self, content, filename): file_parser = RawConfigParser() count = 0 for block in content: count += 1 name_section = "Block-%d" % count file_parser.add_section(name_section) for key in block.keys(): file_parser.set(name_section, key, block[key]) file_parser.write(codecs.open(filename, "w", encoding="utf-8"))
def whitelist_file(tmpdir): name = os.path.join(str(tmpdir), 'whitelist_file') config = RawConfigParser() config['Whitelist'] = {} config['Whitelist']['testevent'] = 'PATH' with open(name, 'w') as f: config.write(f) return name
def default_settings_file(tmpdir): conf = RawConfigParser() conf.optionxform = lambda option: option conf['General'] = { 'UpdateEvery': '60', 'RootFolder': 'root', 'SyncNewCourses': 'False' } f = tmpdir.mkdir('fold').join('sets.ini') with open(str(f), 'w') as setsfile: conf.write(setsfile) return str(f)
def initialization(): rcp = RawConfigParser() rcp.read("taobao/config/settings.cfg") rcp.set('my_settings', 'cookie', '') rcp.set('my_settings', 'keyword', '') rcp.set('my_settings', 'search_api', 'https://s.taobao.com/search?q=') rcp.set('my_settings', 'comment_api', 'https://rate.tmall.com/list_detail_rate.htm?itemId=') rcp.set('my_settings', 'crawl_page', '100') rcp.set('my_settings', 'comment_page', '8') with open('taobao/config/settings.cfg', 'w') as f: rcp.write(f)
def setConfigContent(self, content): conf = RawConfigParser() conf_file = open(self.file_path, 'w') conf_file.write('') conf.read(self.file_path) for section in content: section_items = content[section].items() for option, value in section_items: if conf.has_section(section) == False: conf.add_section(section) conf.set(section, option, value) conf.write(open(self.file_path, "w"))
class ConfigManager(): #------------------------------------------------------------------------------------------ def __init__(self): self._parser = RawConfigParser() self._archivo = None #------------------------------------------------------------------------------------------ def CargarCFG(self, archivo, append=False): self._archivo = archivo if not append: self._parser = RawConfigParser() if archivo.Existe(): self._parser.read(archivo.Ruta()) #------------------------------------------------------------------------------------------ def GuardarCFG(self, archivo=None): if archivo is None: archivo = self._archivo archivo.CarpetaPadre().Crear() with IOEscritor(archivo).Abrir(False, binario=False) as iow: self._parser.write(iow.Stream()) #------------------------------------------------------------------------------------------ def Obtener(self, seccion, clave, valor_default=None): valor = self._parser.get(seccion, clave) if self._parser.has_section( seccion) and self._parser.has_option(seccion, clave) else '' return valor if valor else valor_default #------------------------------------------------------------------------------------------ def ObtenerTodos(self, seccion): return self._parser.items(seccion) if self._parser.has_section( seccion) else [] #------------------------------------------------------------------------------------------ def AgregarSeccion(self, seccion): if not self._parser.has_section(seccion): self._parser.add_section(seccion) #------------------------------------------------------------------------------------------ def Setear(self, seccion, clave, valor): self.AgregarSeccion(seccion) self._parser.set(seccion, clave, valor)
def create_relative_config_file(config_file, manifest, include_corpus=False): if sys.version_info[0] == 3: root = os.path.commonpath(map(os.path.abspath, manifest)) + '/' else: root = os.path.commonprefix(map(os.path.abspath, manifest)) config = ConfigParser({ 'cluster': None, 'corpus_desc': None, 'raw_corpus': None, 'cluster_path': None, 'path': None, 'htrc_metadata': None }) with open(config_file, encoding='utf8') as configfile: config.read_file(configfile) # path variables corpus_file = config.get('main', 'corpus_file') model_pattern = config.get('main', 'model_pattern') cluster_path = config.get('main', 'cluster') path = config.get('main', 'path') raw_corpus = config.get('main', 'raw_corpus') corpus_desc = config.get('main', 'corpus_desc') config.set('main', 'corpus_file', corpus_file.replace(root, '')) config.set('main', 'model_pattern', model_pattern.replace(root, '')) if cluster_path is not None: config.set('main', 'cluster', cluster_path.replace(root, '')) if path is not None: config.set('main', 'path', path.replace(root, '')) if raw_corpus is not None and include_corpus: config.set('main', 'raw_corpus', raw_corpus.replace(root, '')) else: config.set('main', 'raw_corpus', None) if corpus_desc is not None: config.set('main', 'corpus_desc', corpus_desc.replace(root, '')) try: if config.getboolean('main', 'htrc'): htrc_metapath = config.get('www', 'htrc_metadata') if htrc_metapath is not None: config.set('www', 'htrc_metadata', htrc_metapath.replace(root, '')) except: pass tempfh = NamedTemporaryFile(prefix='tez.' + config_file, delete=False) temp_config_file = tempfh.name tempfh.close() with open(temp_config_file, 'w', encoding='utf-8') as tempfile: config.write(tempfile) return temp_config_file
class FactorioLocale: def __init__(self): self.conf = RawConfigParser() self.crap = RawConfigParser() def get_name(self, section, name): return self.conf.get(section, name) or '#%s#%s#' % (section, name) def load(self, csv): conf = RawConfigParser() with open(csv, 'rb') as f: input_bytes = f.read() decoded = input_bytes.decode( chardet.detect(input_bytes)['encoding']) decoded = '[__global__]\n' + decoded conf.read_string(decoded) for sec in conf.sections(): if not self.conf.has_section(sec): self.conf.add_section(sec) self.crap.add_section(sec) for k, v in conf.items(sec): is_crap = False if '__' in v: is_crap = True if not is_crap: if self.conf.has_option(sec, k): if self.conf.get(sec, k).lower() != v.lower(): print('Overwriting locale %s (%r -> %r)' % (k, self.conf.get(sec, k), v)) self.conf.set(sec, k, v) else: if self.crap.has_option(sec, k): print('Overwriting crap locale %s (%r -> %r)' % (k, self.crap.get(sec, k), v)) self.crap.set(sec, k, v) def merge(self): for sec in self.crap.sections(): for k, v in self.crap.items(sec): if not self.conf.has_option(sec, k): print('Using crap locale %s (%r)' % (k, v)) self.conf.set(sec, k, v) def save(self, out): with open(out, 'w') as f: self.conf.write(f)
def save_for_later(self, summary, details, repo, environ, username, password): """""" parser = RawConfigParser() parser.add_section("SUBMIT") parser.set("SUBMIT", "summary", summary) parser.set("SUBMIT", "details", details) parser.set("SUBMIT", "repo", repo) parser.set("SUBMIT", "environ", environ) parser.set("SUBMIT", "username", username) parser.set("SUBMIT", "password", password) filename = os.path.join(os.getenv("PINGUINO_USER_PATH"), "submit-{}".format(datetime.now())) parser.write(open(filename, "w"))
def settingsToFile(insettings, filepath): """Given a dict, save to file in the format specified by configparser""" config = RawConfigParser() config.optionxform = lambda option: option config['General'] = insettings try: dirpath = os.path.dirname(filepath) os.makedirs(dirpath, exist_ok=True) with open(filepath, 'w') as f: config.write(f) except OSError: if not os.path.isdir(dirpath): raise
def generate_token_file(self, token_file, oauth_token, oauth_token_secret): self.oauth_token = oauth_token self.oauth_token_secret = oauth_token_secret conf = RawConfigParser() conf.add_section(SECTION_TOKEN) conf.set(SECTION_TOKEN, 'oauth_token', oauth_token) conf.set(SECTION_TOKEN, 'oauth_token_secret', oauth_token_secret) with open(token_file, 'w') as tokens: conf.write(tokens) print(encode(_('Your account has been saved')))
def update(self): raw = RawConfigParser() raw.add_section('CONFIGURATION') raw.set('CONFIGURATION', 'USEAPPINDICATOR', self.has_app_indicator) raw.set('CONFIGURATION', 'DEFAULTLANGUAGE', self.lang) raw.set('CONFIGURATION', 'VOICESPEED', self.voice_speed) raw.set('CONFIGURATION', 'SHOWNOTIFICATION', self.show_notification) if not os.access(self.path, os.W_OK): return os.makedirs(self.dir, exist_ok=True) print(self.path) with open(self.path, 'w') as stream: raw.write(stream)
def openEqualizer(self): from configparser import RawConfigParser equa = Equalizer(self, Foo.readConfig('audio')) equa.equalize.connect(self.applyEqua) if equa.exec_(): parser = RawConfigParser() parser.read( os.path.dirname(os.path.realpath(__file__)) + '/config') parser['audio']['settings'] = str(equa.config) with open( os.path.dirname(os.path.realpath(__file__)) + '/config', 'w') as configfile: parser.write(configfile)
def create_default(self): """ Create a default settings file """ config = RawConfigParser() configfile = open(self.file_name, "w") config.add_section('Settings') config.set('Settings', 'dark_mode', "0") config.add_section('Plugins') available_plugins = ",".join(self.get_available_plugins()) config.set('Plugins', 'active_plugins', available_plugins) config.write(configfile) configfile.close()
def write_acbs_conf(): acbs_conf_writer = RawConfigParser() acbs_conf_writer.add_section('default') acbs_conf_writer.set('default', 'location', '/var/lib/acbs/repo/') acbs_conf_writer.add_section('acbs') acbs_conf_writer.set('acbs', 'location', '/var/lib/acbs/repo/') try: fp = open('/etc/acbs_forest.conf', 'w') acbs_conf_writer.write(fp) except: err_msg('Unable to write initial configuration file!') return False return True
def write_acbs_conf(): acbs_conf_writer = RawConfigParser() acbs_conf_writer.add_section('default') acbs_conf_writer.set('default', 'location', '/var/lib/abbs/repo/') acbs_conf_writer.add_section('acbs') acbs_conf_writer.set('acbs', 'location', '/var/lib/acbs/repo/') try: fp = open('/etc/acbs_forest.conf', 'w') acbs_conf_writer.write(fp) except: err_msg('Unable to write initial configuration file!') return False return True
def set_property(self, section, property, value): """ Change a property in settings ini file """ config = RawConfigParser() config.read(self.file_name) if section in config.sections(): config.set(section, property, str(value).strip()) configfile = open(self.file_name , "w") config.write(configfile) configfile.close() else: print("Error, the settings file seem to be modified manualy")
def update(self): raw = RawConfigParser() raw.add_section('CONFIGURATION') raw.set('CONFIGURATION', 'USEAPPINDICATOR', self.has_app_indicator) raw.set('CONFIGURATION', 'DEFAULTLANGUAGE', self.lang) raw.set('CONFIGURATION', 'VOICESPEED', self.voice_speed) raw.set('CONFIGURATION', 'SHOWNOTIFICATION', self.show_notification) try: os.makedirs(self.dir, exist_ok=True) with open(self.path, 'w+') as stream: raw.write(stream) except Exception: return False return True
def patch_config(root, name, patch_cb, **kwargs): # treat comment line as values, to have them back in output config = RawConfigParser(comment_prefixes=None, empty_lines_in_values=False, allow_no_value=True) config.optionxform = lambda option: option filename = f'{root}/resources/config-{name}.properties' config.read(filename) patch_cb(config, **kwargs) with open(filename, 'wt', encoding='utf8') as output_file: config.write(output_file)
def install_script(conf_dir: str, group: str): """ Function copies script and config files to needed directories :param conf_dir: Path to config directory to create :type: str :param group: Group name to set chown root:group to config directory :type: str :return: True or False :rtype: bool """ conf_file = conf_dir + '/zbx-rc.conf' try: # Create config directory and assign rights if not os.path.exists(conf_dir): # Create new config file cfg = RawConfigParser() cfg.add_section('RCHAT') cfg.set('RCHAT', 'protocol', 'https') cfg.set('RCHAT', 'server', 'rocketchat.mts-nn.ru') cfg.set('RCHAT', 'port', '443') cfg.set('RCHAT', 'uid', '') cfg.set('RCHAT', 'token', '') # Zabbix API connection info cfg.add_section("ZABBIX") cfg.set("ZABBIX", "zbx_server", "http://zabbix") cfg.set("ZABBIX", "zbx_api_user", "user") cfg.set("ZABBIX", "zbx_api_pass", "password") cfg.set("ZABBIX", "zbx_tmp_dir", "/tmp") # Create directory os.mkdir(conf_dir, mode=0o655) # Write file to disk with open(conf_file, 'w') as file: cfg.write(file) os.chmod(conf_file, 0o640) try: os.chown(conf_dir, 0, grp.getgrnam(group).gr_gid) return True except KeyError: print( 'WARNING: Cannot find group "{}" to set rights to "{}". Using "root".' .format(group, conf_dir)) os.chown(conf_dir, 0, 0) return False except PermissionError: raise SystemExit( 'PERMISSION ERROR: You have no permissions to create "{}" directory.' .format(conf_dir))
def config_file(tempdir, default_config): """Yields path to a configuration file suitable for testing.""" cfg = RawConfigParser() cfg.add_section('altsrc') for key, value in default_config.items(): cfg.set('altsrc', key, value) filename = '%s/altsrc-test.cfg' % tempdir with open(filename, 'w') as fh: cfg.write(fh) yield filename os.unlink(filename)
def get_config(): config = RawConfigParser() if not os.path.exists(INSTALL_DIR): os.mkdir(INSTALL_DIR) if not os.path.exists(CONFIG_FILE): config["fsociety"] = DEFAULT_CONFIG with open(CONFIG_FILE, "w") as configfile: config.write(configfile) config.read(CONFIG_FILE) check_config(config) if config.get("fsociety", "version") != __version__: config.set("fsociety", "version", __version__) write_config(config) return config