def write_sts_token(self, profile, access_key_id, secret_access_key, session_token, region=None): """ Writes STS auth information to credentials file """ region = region or self.region output = 'json' if not os.path.exists(self.creds_dir): os.makedirs(self.creds_dir) config = SafeConfigParser() 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) config.set(profile, 'aws_security_token', session_token) with open(self.creds_file, 'w+') as configfile: config.write(configfile) print("Temporary credentials written to profile: %s" % profile) self.logger.info("Invoke using: aws --profile %s <service> <command>" % profile)
def generate_defaults(): """Tries to generate the default run configuration files from the paths specified in chilin.conf. The idea is that an admin, who is installing ChiLin system-wide could define the defaults which will allow users to avoid generating/editing conf files!! """ cf = SafeConfigParser() cf.add_section('basics') ls = ['id', 'time', 'species', 'input', 'output'] for fld in ls: cf.set('basics', fld, '$' + fld.upper()) #SET the chilin version number cf.set('basics', "version", version) #read in the chilin.conf file--look first for developer defaults if os.path.exists('gcap.conf.filled'): cf.read('gcap.conf.filled') else: cf.read('gcap.conf') #write the template file! f = open(os.path.join('gcap', 'static', 'gcap.conf.filled'), 'w') cf.write(f) f.close()
def save(self, configfile = None): """ write state to cfg file """ config = Config() section = 'explosion' config.add_section(section) config.set(section,'alpha' ,'{:g}'.format(self.alpha)) config.set(section,'precision','{:g}'.format(self.precision)) config.set(section,'limit' ,'{:g}'.format(self.limit)) config.set(section,'goal' ,'{:g}'.format(self.goal)) config.set(section,'flag' ,'{:s}'.format(self.flag)) config.set(section,'base' ,'{:s}'.format(self.basename)) if self.best is not None: self.best.add_to_config( config = config, section = 'best') if self.hi is not None: self.hi.add_to_config( config = config, section = 'hi') if self.lo is not None: self.lo.add_to_config( config = config, section = 'lo') with open(configfile,'w') as f: config.write(f)
def generate_config(**kwargs): path = os.path.join(tmpdir.strpath, 'test_config') with open(path, 'w') as fobj: config = SafeConfigParser() config.add_section('Client') config.set('Client', 'cwd', kwargs.get('cwd', '.')) config.set('Client', 'tmp_filename', kwargs.get('tmp_filename', 'test_tmp_fact.pickle')) config.set('Client', 'log_level', kwargs.get('log_level', 'debug')) config.set('Client', 'log_console', kwargs.get('log_console', '0')) config.set('Client', 'log_file', kwargs.get('log_file', '0')) config.set('Client', 'log_filename', kwargs.get('log_filename', faker.file_name())) config.set('Client', 'dbus', kwargs.get('dbus', '0')) config.add_section('Backend') config.set('Backend', 'unsorted_localized', kwargs.get( 'unsorted_localized', 'Unsorted')) config.set('Backend', 'store', kwargs.get('store', 'sqlalchemy')) config.set('Backend', 'daystart', kwargs.get('daystart', '00:00:00')) config.set('Backend', 'db_path', kwargs.get('db_path', 'postgres://*****:*****@localhost/hamsterlib')) config.set('Backend', 'fact_min_delta', kwargs.get('fact_min_delta', '60')) config.write(fobj) return path
def generate_config(**kwargs): path = os.path.join(tmpdir.strpath, 'test_config') with open(path, 'w') as fobj: config = SafeConfigParser() config.add_section('Client') config.set('Client', 'cwd', kwargs.get('cwd', '.')) config.set('Client', 'tmp_filename', kwargs.get('tmp_filename', 'test_tmp_fact.pickle')) config.set('Client', 'log_level', kwargs.get('log_level', 'debug')) config.set('Client', 'log_console', kwargs.get('log_console', '0')) config.set('Client', 'log_file', kwargs.get('log_file', '0')) config.set('Client', 'log_filename', kwargs.get('log_filename', faker.file_name())) config.set('Client', 'dbus', kwargs.get('dbus', '0')) config.add_section('Backend') config.set('Backend', 'unsorted_localized', kwargs.get('unsorted_localized', 'Unsorted')) config.set('Backend', 'store', kwargs.get('store', 'sqlalchemy')) config.set('Backend', 'daystart', kwargs.get('daystart', '00:00:00')) config.set( 'Backend', 'db_path', kwargs.get( 'db_path', 'postgres://*****:*****@localhost/hamsterlib')) config.set('Backend', 'fact_min_delta', kwargs.get('fact_min_delta', '60')) config.write(fobj) return path
def addRepo(self, params): """ Add a given repository to YumBase """ # At least one base url, or one mirror, must be given. baseurl = params.get('baseurl', '') config = params.get('config', {}) mirrorlist = config.get('mirrorlist', '') metalink = config.get('metalink', '') if not baseurl and not mirrorlist and not metalink: raise MissingParameter('GGBREPOS0013E') if baseurl: validate_repo_url(get_expanded_url(baseurl)) if mirrorlist: validate_repo_url(get_expanded_url(mirrorlist)) if metalink: validate_repo_url(get_expanded_url(metalink)) if mirrorlist and metalink: raise InvalidOperation('GGBREPOS0030E') repo_id = params.get('repo_id', None) if repo_id is None: repo_id = 'gingerbase_repo_%s' % str(int(time.time() * 1000)) repos = self._get_repos('GGBREPOS0026E') if repo_id in repos.keys(): raise InvalidOperation('GGBREPOS0022E', {'repo_id': repo_id}) repo_name = config.get('repo_name', repo_id) repo = { 'baseurl': baseurl, 'mirrorlist': mirrorlist, 'name': repo_name, 'gpgcheck': 1, 'gpgkey': [], 'enabled': 1, 'metalink': metalink } # write a repo file in the system with repo{} information. parser = SafeConfigParser() parser.add_section(repo_id) for key, value in repo.items(): if value: parser.set(repo_id, key, value) repofile = os.path.join(self._confdir, repo_id + '.repo') try: with open(repofile, 'w') as fd: parser.write(fd) except Exception: raise OperationFailed('GGBREPOS0018E', {'repo_file': repofile}) return repo_id
def save_config(): if app.config['SCHEDULE_ENCODINGS_SAVE'] == True: value_scheduler = "enabled" else: value_scheduler = "disabled" if app.config['SAVE_UNKNOWN'] == True: value_saveunknown = "enabled" else: value_saveunknown = "disabled" if app.config['ACCELERATION'] == True: value_acceleration = "enabled" else: value_acceleration = "disabled" parser = SafeConfigParser() parser.read('config.cfg') for each_section in parser.sections(): parser.remove_section(each_section) parser.add_section('FRCONFIG') parser.set('FRCONFIG', 'scheduler', value_scheduler) parser.set('FRCONFIG', 'saveunknown', value_saveunknown) parser.set('FRCONFIG', 'acceleration', value_acceleration) parser.set('FRCONFIG', 'hour', str(app.config['SCHEDULE_ENCODINGS_HOUR'])) parser.set('FRCONFIG', 'minutes', str(app.config['SCHEDULE_ENCODINGS_MINUTES'])) new_config_file = open('config.cfg', 'w') parser.write(new_config_file) new_config_file.close() return "succes"
def createTemplate(self, configfilename='config_sample.conf'): dict_sample = dict([('00-info', { 'author': 'Tong Zhang', 'note': '', 'created_time': time.strftime('%Y-%m-%d %H:%M:%S %Z', time.localtime()) }), ('01-facility', { 'country': 'China', 'name': 'SDUV', 'affiliation': 'SINAP' }), ('02-electron_beam', { 'normalized_emittance(m)': '4e-6', 'peak_current(A)': '300', 'central_energy(MeV)': '150', 'average_beta_function(m)': '4', 'bunch_charge(C)': '0.2e-9', 'energy_spread': '1e-4', 'bunch_shape': 'gaussian' }), ('03-undulator', { 'total_length(m)': '10', 'period_length(m)': '0.04' }), ('04-FEL_radiation', { 'wavelength(m)': '350e-9' })]) parser_sample = SafeConfigParser() for section_name in sorted(dict_sample.keys()): parser_sample.add_section(section_name) [ parser_sample.set(section_name, k, v) for k, v in sorted(dict_sample[section_name].items()) ] parser_sample.write(open(configfilename, 'w'))
class GitConfigParser(): CORE = 'core' def __init__(self, branch): self.section = branch self.file = join(GIT_DIR, '.git', 'gitcc') self.parser = SafeConfigParser(); self.parser.add_section(self.section) def set(self, name, value): self.parser.set(self.section, name, value) def read(self): self.parser.read(self.file) def write(self): self.parser.write(open(self.file, 'w')) def getCore(self, name, *args): return self._get(self.CORE, name, *args) def get(self, name, *args): return self._get(self.section, name, *args) def _get(self, section, name, default=None): if not self.parser.has_option(section, name): return default return self.parser.get(section, name) def getList(self, name, default=None): return self.get(name, default).split('|') def getInclude(self): return self.getCore('include', '.').split('|') def getExclude(self): return self.getCore('exclude', '.').split('|') def getBranches(self): return self.getList('branches', 'main') def getExtraBranches(self): return self.getList('_branches', 'main')
class Config(object): """ The configuration object for a link to a database. """ def __init__(self, section=None, config_file=None): self.parser = SafeConfigParser()#allow_no_value=True) default_file = os.path.expanduser('~/.EMIS/pyEMIS.ini') if not config_file: config_file = default_file self.config_file = config_file if not section: section = 'DEFAULT' self.section = section read_files = self.parser.read(self.config_file) if not read_files: self.parser.add_section(self.section) with open(default_file, 'wb') as configfile: self.parser.write(configfile) if not self.parser.has_section(self.section): raise ConfigurationFileError('Section [%s] not found in configuration file (sections = %s).' % (self.section, self.parser.sections()), self.config_file) def __getattr__(self, name): try: return self.parser.get(self.section, name) except NoSectionError as e: raise ConfigurationFileError('Section [%s] not found in configuration file (sections = %s).' % (self.section, self.parser.sections()), self.config_file) except NoOptionError as e: raise ConfigurationFileError('Option "%s = ..." not in section [%s] of configuration file (options = %s).' % (name, self.section, self.parser.options(self.section)), self.config_file)
def loadJson(self, data): #import rpdb2; rpdb2.start_embedded_debugger('test') newConf = SafeConfigParser() try: config = json.loads(data) except ValueError as e: raise e try: for kSec, vSec in config.items(): try: newConf.add_section(kSec) except NoSectionError: pass for kVal, vVal in vSec.items(): try: newConf.set(kSec, kVal, str(vVal['value']).replace('%', '%%')) except NoSectionError as e: pass except Exception as e: #import rpdb2; rpdb2.start_embedded_debugger('test') print(e) # now replace self._proxies = newConf._proxies self._sections = newConf._sections self.notify(FLSConfiguration.STATE_CHANGED)
def initialise(self, data=None, overwrite=True): """ Create a new configuration file. If data is a dict the new configuration file will include the data as {section: {key: value}} """ # No clobber option if not overwrite and self.exists(): raise OSError("Will not overwrite existing configuration {0}." "".format(self.path)) # Might not exist on the first run try: os.makedirs(config_dir) # PY2; use exist_ok=True in PY3 except OSError: # Exists pass # Build up from a blank configuration new_config = SafeConfigParser() if data is not None: for section in data: new_config.add_section(section) for option, value in data[section].items(): new_config.set(section, option, value) with open(self.path, 'w') as cfg_file: new_config.write(cfg_file) # become the new file self.read(self.path)
def saveConfig(self): if len(self.jiraID.text()) == 0 or len( self.jiraUsername.text()) == 0 or len( self.jiraPassword.text()) == 0 or len( self.jiraPassword.text()) == 0 or len( self.boardName.text()) == 0 or len( self.boardID.text()) == 0 or len( self.jiraLink.text()) == 0: error_dialog = QErrorMessage(self) error_dialog.showMessage('Please enter all the textfields.') else: configFile = open("adapter_config.ini", "w") configFile.truncate() configFile.close() config = SafeConfigParser() config.read('adapter_config.ini') config.add_section('jiraout') config.set('jiraout', 'jiraid', self.jiraID.text()) config.set('jiraout', 'jirausername', self.jiraUsername.text()) config.set('jiraout', 'jirapassword', self.jiraPassword.text()) config.set('jiraout', 'boardname', self.boardName.text()) config.set('jiraout', 'boardid', self.boardID.text()) config.set('jiraout', 'jiralink', self.jiraLink.text()) with open('adapter_config.ini', 'w') as f: config.write(f)
def generate_defaults(): """Tries to generate the default run configuration files from the paths specified in chilin.conf. The idea is that an admin, who is installing ChiLin system-wide could define the defaults which will allow users to avoid generating/editing conf files!! """ cf = SafeConfigParser() cf.add_section('basics') ls = ['id', 'time', 'species', 'input', 'output'] for fld in ls: cf.set('basics', fld, '$'+fld.upper()) #SET the chilin version number cf.set('basics', "version", version) #read in the chilin.conf file--look first for developer defaults if os.path.exists('gcap.conf.filled'): cf.read('gcap.conf.filled') else: cf.read('gcap.conf') #write the template file! f = open(os.path.join('gcap','static','gcap.conf.filled'),'w') cf.write(f) f.close()
class GitConfigParser(): CORE = 'core' def __init__(self, branch): self.section = branch self.file = join(GIT_DIR, '.git', 'gitcc') self.parser = SafeConfigParser(); self.parser.add_section(self.section) def set(self, name, value): self.parser.set(self.section, name, value) def read(self): self.parser.read(self.file) def write(self): self.parser.write(open(self.file, 'w')) def getCore(self, name, *args): return self._get(self.CORE, name, *args) def get(self, name, *args): return self._get(self.section, name, *args) def _get(self, section, name, default=None): if not self.parser.has_option(section, name): return default return self.parser.get(section, name) def getList(self, name, default=None): return self.get(name, default).split('|') def getInclude(self): return self.getCore('include', '.').split('|') def getBranches(self): return self.getList('branches', 'main') def getExtraBranches(self): return self.getList('_branches', 'main')
def test_database(self): tmpfile = NamedTemporaryFile() config = SafeConfigParser() config.add_section("database") config.set("database", "engine", "django.db.backends.mysql") config.set("database", "host", "db.example.com") config.set("database", "name", "example") config.set("database", "password", "secret") config.set("database", "port", "3306") config.set("database", "user", "jdoe") config.write(tmpfile) tmpfile.flush() environ["DJANGO_INSTALLER_SETTINGS"] = tmpfile.name env = {} exec(IMPORT_MAGIC, env) self.assertEqual(env.keys(), IMPORTED_GLOBALS + ['DATABASES']) self.assertEqual(env['DATABASES'], { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'example', 'HOST': 'db.example.com', 'USER': '******', 'PASSWORD': '******', 'PORT': '3306', } })
async def on_ready(): print('Logged in as') print(client.user.name) print(client.user.id) print('------') print(about_msg) # Create giveaway section in config if it doesn't exist config = SafeConfigParser() config.read('config.ini') if not config.has_section('giveaway'): config.add_section('giveaway') config.set('giveaway', 'rank_restriction', 'False') with open('config.ini', 'w') as f: config.write(f) gw2 = discord.Game(name="Guild Wars 2", type=0) status = discord.Status("online") await client.change_presence(game=gw2, status=status) # Check if a giveaway was going on before the previous boot global giveaway_is_running resultset = session.query(Giveaway) if resultset.count() > 0: giveaway_is_running = True
def config(): PATH = ('%s/config.ini' % directory) if os.path.isfile(PATH) and os.access(PATH, os.R_OK): print("Config exists and is readable") else: print("Either config is missing or is not readable") config = SafeConfigParser() config.read(PATH) config.add_section('Bot') config.add_section('MySQL') config.set('Bot', 'debug', 'False') config.set('Bot', 'Token', 'token') config.set('Bot', 'OwnerID', 'id') config.set('Bot', 'SteamAPI', 'key') config.set('Bot', 'TwitchSecret', 'ClientID') config.set('Bot', 'WeatherUndergroundAPI', 'APIKEY') config.set('MySQL', 'IP', '127.0.0.1') config.set('MySQL', 'PORT', '3306') config.set('MySQL', 'DB', 'example_db') config.set('MySQL', 'USER', 'USER') config.set('MySQL', 'PASS', 'PASS') with open(PATH, 'w') as f: config.write(f)
def _load_schema(self, location, xml=None): """ location -- location of schema, also used as a key xml -- optional string representation of schema """ cachedir = self._cachedir # wsdl2py: deal with XML Schema if not os.path.isdir(cachedir): os.mkdir(cachedir) file = os.path.join(cachedir, '.cache') section = 'TYPES' cp = ConfigParser() try: cp.readfp(open(file, 'r')) except IOError: del cp; cp = None option = location.replace(':', '-') # colons seem to screw up option if (cp is not None and cp.has_section(section) and cp.has_option(section, option)): types = cp.get(section, option) else: # dont do anything to anames if not self._pyclass: containers.ContainerBase.func_aname = lambda instnc,n: str(n) from pysphere.ZSI.wstools import XMLSchema reader = XMLSchema.SchemaReader(base_url=location) if xml is not None and isinstance(xml, str): schema = reader.loadFromString(xml) elif xml is not None: raise RuntimeError('Unsupported: XML must be string') elif not os.path.isfile(location): schema = reader.loadFromURL(location) else: schema = reader.reader.loadFromFile(location) # TODO: change this to keyword list class options: output_dir = cachedir schema = True simple_naming = False address = False lazy = self._lazy complexType = self._pyclass schema.location = location files = commands._wsdl2py(options, schema) if cp is None: cp = ConfigParser() if not cp.has_section(section): cp.add_section(section) types = filter(lambda f: f.endswith('_types.py'), files)[0] cp.set(section, option, types) cp.write(open(file, 'w')) if os.path.abspath(cachedir) not in sys.path: sys.path.append(os.path.abspath(cachedir)) mod = os.path.split(types)[-1].rstrip('.py') return __import__(mod)
def update(self, section, option, value): parser = SafeConfigParser() parser.read(self.config_path) if not parser.has_section(section): parser.add_section(section) parser.set(section, option, str(value)) with open(self.config_path, "w+") as configfile: parser.write(configfile)
def _load_schema(self, location, xml=None): """ location -- location of schema, also used as a key xml -- optional string representation of schema """ cachedir = self._cachedir # wsdl2py: deal with XML Schema if not os.path.isdir(cachedir): os.mkdir(cachedir) _file = os.path.join(cachedir, '.cache') section = 'TYPES' cp = ConfigParser() try: cp.readfp(open(_file, 'r')) except IOError: del cp; cp = None option = location.replace(':', '-') # colons seem to screw up option if (cp is not None and cp.has_section(section) and cp.has_option(section, option)): types = cp.get(section, option) else: # dont do anything to anames if not self._pyclass: containers.ContainerBase.func_aname = lambda instnc,n: str(n) from pysphere.ZSI.wstools import XMLSchema reader = XMLSchema.SchemaReader(base_url=location) if xml is not None and isinstance(xml, str): schema = reader.loadFromString(xml) elif xml is not None: raise RuntimeError('Unsupported: XML must be string') elif not os.path.isfile(location): schema = reader.loadFromURL(location) else: schema = reader.reader.loadFromFile(location) # TODO: change this to keyword list class options: output_dir = cachedir schema = True simple_naming = False address = False lazy = self._lazy complexType = self._pyclass schema.location = location files = commands._wsdl2py(options, schema) if cp is None: cp = ConfigParser() if not cp.has_section(section): cp.add_section(section) types = [f for f in files if f.endswith('_types.py')][0] cp.set(section, option, types) cp.write(open(_file, 'w')) if os.path.abspath(cachedir) not in sys.path: sys.path.append(os.path.abspath(cachedir)) mod = os.path.split(types)[-1].rstrip('.py') return __import__(mod)
def createPreferencesFile(self, file): createParser = SafeConfigParser() createParser.add_section('info') createParser.set('info', 'version', '0.1') createParser.add_section('settings') dbPath = self.getContentDir() + '/tom-db.sqlite' createParser.set('settings', 'sqlitePath', dbPath) with open(file, 'w+') as iniFile: createParser.write(iniFile)
def read_config(config_file): logger.info('Reading config file ' + args.config_file) global config config = SafeConfigParser() config.add_section('controlsocket') # config.set('controlsocket', 'interface', 'localhost') config.set('controlsocket', 'port', '6587') config_files_read = config.read(config_file) logger.debug('Successfully read ' + ', '.join(config_files_read))
def __init__(self, options, gitlab_host): self.options = options self.config = find_config(self.options.config) # Get the host from upstream and remove the https:// # the case for alpine linux, https://gitlab.alpinelinux.org # will be reduced to gitlab.alpinelinux.org # # Do note that it does not matter if we the origin or upstream # remote is used here since gitlab is not federated, so both will # call the same server self.section = gitlab_host.replace("https://", "") """ Write the configuration passed to us via the CLI to the config file if it's not there already or the user wants to overwrite it """ parser = SafeConfigParser() parser.read(self.config) if parser.has_section(self.section) is False: parser.add_section(self.section) with open(self.config, "w") as c: parser.write(c) # In case the 'url' options is not set in the section we are looking for # then just write it out. if parser.has_option(self.section, "url") is False: parser[self.section]["url"] = "https://" + self.section with open(self.config, "w") as c: parser.write(c) if parser.has_option(self.section, "private_token") is False or ( self.options.overwrite is True): # If --token is not passed to us then drop out with a long useful # message, if it is passed to us write it out in the configuration # file if self.options.token is None: token_answer = dict() token_answer["token"] = "" print("Please visit https://" + self.section + "/profile/personal_access_tokens to generate your token") while token_answer is not None and token_answer["token"] == "": questions = [ inquirer.Text("token", message="personal access token") ] token_answer = inquirer.prompt(questions) if token_answer is None: raise ValueError("personal access token not provided") else: parser[ self.section]["private_token"] = token_answer["token"] with open(self.config, "w") as c: parser.write(c) else: parser[self.section]["private_token"] = self.options.token with open(self.config, "w") as c: parser.write(c)
def dumpDictToConfig(self, newhierdict, configfilename): newparser = SafeConfigParser() newparser.optionxform = str for section_name in sorted(newhierdict.keys()): newparser.add_section(section_name) [ newparser.set(section_name, k, v) for k, v in sorted(newhierdict[section_name].items()) ] newparser.write(open(configfilename, 'w'))
def setConnectionFile(self): config = SafeConfigParser() config.read(self.configFile) if not config.has_section('main'): config.add_section('main') config.set('main', 'command_executor', self.driver.command_executor._url) config.set('main', 'session_id', self.driver.session_id) with open(self.configFile, 'w') as f: config.write(f)
def save(cls): """Save the all configuration in the config file.""" config = SafeConfigParser() # Make option section config.add_section('options') for key, value in cls.config.iteritems(): config.set('options', str(key), unicode(value)) # Write the config with codecs.open(CONFIG_FILE, 'w+', encoding='utf8') as f: config.write(f)
class AospConfig: def __init__(self, config_directory): self.config_directory = config_directory self.config_file = os.path.join(config_directory, 'config') self.dirty = False self.config = SafeConfigParser() self.config.read(self.config_file) def write(self): if not self.dirty: return # Check if dir exists if os.path.isdir(self.config_directory) == False: os.makedirs(self.config_directory) with open(self.config_file, 'w') as f: self.config.write(f) def set(self, section, option, value): if not self.config.has_section(section): self.config.add_section(section) self.config.set(section, option, value) self.dirty = True def get(self, section, option): try: return self.config.get(section, option) except Exception: return None def remove_option(self, section, option): try: self.config.remove_option(section, option) self.dirty = True return True except Exception: return False def remove_section(self, section): try: self.config.remove_section(section) self.dirty = True return True except Exception: return False def remove_configuration(self): self.dirty = False self.config = SafeConfigParser() shutil.rmtree(self.config_directory)
def _write_defaults(path): if not path.parent == "" and not path.parent.exists(): path.parent.makedirs() cp = SafeConfigParser() for section, values in _options.items(): cp.add_section(section) for name, value in values.items(): cp.set(section, name, str(value.default)) with open(path, "w") as f: cp.write(f)
def generate_config(configdata=None): log.debug("Generating config") global _old_data if not configdata: configdata = data for k, v in data.items(): if callable(v): data[k] = v() config = SafeConfigParser(allow_no_value=True, interpolation=None) sect = APPNAME config.add_section(sect) config.set(sect, "; This file will regenerate itself if you f**k it up.") config.set(sect, "; :)\n") config.set(sect, "\n; Where to save the images") config.set(sect, "img_dir", configdata["img_dir"]) config.set(sect, "\n; How to format the date/time") config.set( sect, "; See http://strftime.org/ or " "https://docs.python.org/3.6/library/datetime.html" "#strftime-and-strptime-behavior for a reference") config.set( sect, "; '%c' gives a complete date and time " "appropriate to your locale") config.set( sect, "; '%a %d %B %Y %H:%M' is nice and human-readable " "- it looks like 'Sat 16 June 2018 09:00'") config.set(sect, "; '%Y-%m-%d %H%M' should be easy to sort and browse") config.set(sect, "strftime", configdata["strftime"]) config.set(sect, "\n; Image filename format") config.set( sect, "; {strftime} is a placeholder " "for the date the image was captured " "where the time is formatted as specified " "in the 'strftime' option ") config.set(sect, "; You might like to use 'Desktop - {strftime}.png'") config.set( sect, "; You can choose not to include {strftime} at all" " but then every new image would overwrite the previous one.") config.set( sect, "; The image format is based on the extension" ", so you can use .png, .jpg, and so on " "and the image will be in that format.") config.set(sect, "filename", configdata["filename"]) write_cfg(config) _old_data = configdata.copy()
def savebook(self): parser = SafeConfigParser() for entry in self.entries.values(): section = entry.nickname() parser.add_section(section) parser.set(section, "givenname", entry.givenname()) parser.set(section, "surname", entry.surname()) parser.set(section, "organization", entry.organization()) parser.set(section, "sip", entry.sip()) file = open(self._filename, "w") parser.write(file) file.close()
def setStarted(self, setBol): config = SafeConfigParser() config.read(self.configFile) if not config.has_section('main'): config.add_section('main') if setBol: pid = os.getpid() config.set('main', 'started', str(pid)) else: if config.has_option('main', 'started'): config.remove_option('main', 'started') with open(self.configFile, 'w') as f: config.write(f)
def save_to_dot_config(self): filename = os.path.expanduser('~/.osccaprc') parser = SafeConfigParser() fd = open(filename, 'r') parser.readfp(fd) try: parser.add_section('global') except configparser.DuplicateSectionError: pass parser.set('global', 'last_active_scope', str(self.active_scope_id)) fd = open(filename + '~', 'w') parser.write(fd) os.rename(filename + '~', filename)
def merge_write(self, fileobject): """ Update section contents of ``fileobject.name`` by section only. """ scp = SafeConfigParser() # Safe if file doesn't exist scp.read(fileobject.name) # N/B: This won't work with DEFAULTS if not scp.has_section(self._section): scp.add_section(self._section) for key, value in list(self.items()): scp.set(self._section, key, value) scp.write(open(fileobject.name, "w+b")) # truncates file first
def _write_missing(path): cp = SafeConfigParser() cp.read(path) for section, values in _options.items(): if not cp.has_section(section): cp.add_section(section) for name, value in values.items(): if not cp.has_option(section, name): cp.set(section, name, str(value.default)) with open(path, "w") as f: cp.write(f)
async def givecredit(self, ctx, user: discord.Member, amount): """ Used for adding credits to a member's wallet (in case of prizes, etc) """ config = SafeConfigParser() currenttime = datetime.datetime.now() user = str(user.id) config.read('wallet.ini') if config.has_section(user): balance = int(config.get('{}'.format(user), 'balance')) balance = balance + int(amount) balance = str(balance) config.set('{}'.format(user), 'balance', "{}".format(balance)) config.set('{}'.format(user), 'lastused', '{}'.format(currenttime)) with open('wallet.ini', 'w') as f: config.write(f) embed = discord.Embed( title='Added Balance', description='Your balance has been updated successfully!', color=0xFFD000) embed.add_field( name='Balance', value='{} has given you {} credit(s)! Your balance is now {}.'. format(ctx.message.author, amount, balance), inline=True) embed.set_thumbnail(url='https://i.imgur.com/akZqYz8.png') await self.bot.say(embed=embed) else: config.add_section('{}'.format(user)) config.set('{}'.format(user), 'lastused', '{}'.format(currenttime)) credits = int(amount) + 150 credits = str(credits) config.set('{}'.format(user), 'balance', '{}'.format(credits)) with open('wallet.ini', 'w') as f: config.write(f) balance = int(config.get('{}'.format(user), 'balance')) embed = discord.Embed( title='Created Wallet', description= 'Your wallet has been created and updated successfully!', color=0xFFD000) embed.add_field( name='Balance', value='{} has given you {} credit(s)! Your balance is now {}.'. format(ctx.message.author, amount, balance), inline=True) embed.set_thumbnail(url='https://i.imgur.com/akZqYz8.png') await self.bot.say(embed=embed)
def __read_config(self): cfg = SafeConfigParser() cfgpath = get_config_file() add_section = False if not os.path.exists(cfgpath): log("Could not find " + cfgpath + ", trying to create one") add_section = True else: cfg.read(cfgpath) try: cfg.get("main", "VSPATH") cfg.get("main", "target_architecture") except: add_section = True if add_section: DIR = os.environ.get("VSINSTALLDIR") if DIR is None: die("Could not work out which studio you are using, make sure you run dobmake.py in a Visual Studio command prompt." ) if target_architecture is None: die("No target_architecture set. Please specify on command line, using the --target switch." ) if not cfg.has_section("main"): cfg.add_section("main") cfg.set("main", "VSPATH", os.path.join(DIR, "Common7", "Tools")) cfg.set("main", "target_architecture", target_architecture) with open(cfgpath, "w") as configfile: cfg.write(configfile) elif target_architecture is not None and cfg.get( "main", "target_architecture") != target_architecture: #if it is set on the command line we want to write that value cfg.set("main", "target_architecture", target_architecture) with open(cfgpath, "w") as configfile: cfg.write(configfile) self.studio = os.path.normcase( os.path.normpath(cfg.get("main", "VSPATH"))) self.arch = cfg.get("main", "target_architecture") if not os.path.isdir(self.studio) or not os.path.isfile( os.path.join(self.studio, os.pardir, os.pardir, "VC", "vcvarsall.bat")): die("Something seems to have happened to your dobmake.ini or Visual Studio installations!" + "\nVSPATH (in dots_generated/dobmake.ini) does not seem to point to a valid path." + "\nTry to delete dots_generated/dobmake.ini and run dobmake.py in a Visual Studio command prompt." )
def _config_to_configparser(self, config): """ Return a ConfigParser instance representing a given config dictionary. Args: config (dict): Dictionary of config key/value pairs. Returns: SafeConfigParser: SafeConfigParser instance representing config. """ def get_store(): return config['store'] def get_day_start(): return config['day_start'].strftime('%H:%M:%S') def get_fact_min_delta(): return text_type(config['fact_min_delta']) def get_tmpfile_path(): return text_type(config['tmpfile_path']) def get_db_engine(): return config['db_engine'] def get_db_path(): return text_type(config['db_path']) def get_autocomplete_activities_range(): return text_type(config['autocomplete_activities_range']) def get_autocomplete_split_activity(): return text_type(config['autocomplete_split_activity']) cp_instance = SafeConfigParser() cp_instance.add_section('Backend') cp_instance.set('Backend', 'store', get_store()) cp_instance.set('Backend', 'day_start', get_day_start()) cp_instance.set('Backend', 'fact_min_delta', get_fact_min_delta()) cp_instance.set('Backend', 'tmpfile_path', get_tmpfile_path()) cp_instance.set('Backend', 'db_engine', get_db_engine()) cp_instance.set('Backend', 'db_path', get_db_path()) cp_instance.add_section('Frontend') cp_instance.set('Frontend', 'autocomplete_activities_range', get_autocomplete_activities_range()) cp_instance.set('Frontend', 'autocomplete_split_activity', get_autocomplete_split_activity()) return cp_instance
def _settings_parser(default_notes_dir='~/minion/notes'): ''' Create the parser for the settings file. Include sensible default values. ''' # Default notes settings settings = SafeConfigParser() settings.add_section('notes') settings.set('notes', 'home', default_notes_dir) settings.set('notes', 'favorites', 'inbox, today, next, soon, someday') settings.set('notes', 'notes_included_extensions', '*') settings.set('notes', 'notes_excluded_extensions', '~') settings.set('notes', 'default_template', 'note') settings.set('notes', 'default_recent_days', '14') settings.set('notes', 'archive_folders_date_format', '%%y.%%m') # Default composition settings settings.add_section('compose') default_template_dir = os.path.join(os.path.dirname(__file__), 'templates') settings.set('compose', 'templates', default_template_dir) settings.set('compose', 'extension', '.txt') settings.set('compose', 'filename_sep', '-') settings.set('compose', 'editor', 'vim') settings.set('compose', 'tagline', ':tags:') settings.set('compose', 'tags_case_sensitive', 'false') # Default note date format settings.add_section('date') settings.set('date', 'format', '%%Y-%%m-%%d') # Sort actions settings.add_section('sort_actions') return settings
def connectWithParams(self, port, baudRate, parity, stopBits, flowControl): config = SafeConfigParser() config.read(settingsPath) if not config.has_section(settingsSection): config.add_section(settingsSection) config.set(settingsSection, settingsKeyPort, port) config.set(settingsSection, settingsKeyBaudRate, baudRate) config.set(settingsSection, settingsKeyParity, parity) config.set(settingsSection, settingsKeyStopBits, str(stopBits)) config.set(settingsSection, settingsKeyFlowControl, str(flowControl)) with open(settingsPath, 'w') as f: config.write(f) self.connect()
class Config(): def __init__(self, path=CONFIGPATH): self.this_parser = SafeConfigParser() self.path = path self.read() self.data = {} self.get_values() def update(self, section, option, newvalue, update_file=True): section_value = self.data.get(section) if not section_value: self.this_parser.add_section(section) section_value = {} section_value.update({option: newvalue}) self.data.update({section: section_value}) self.this_parser.set(section, option, newvalue) if update_file: self.dump() def read(self): try: self.this_parser.read(self.path) except: print('Error on reading user configuration') def get_values(self): if self.this_parser.sections() == []: print(f'Failed to load {self.path}') else: for section in self.this_parser.sections(): self.data[section] = self.settingsMap(section) def dump(self): # Writing our configuration file to 'example.cfg' with open(self.path, 'w') as configfile: self.this_parser.write(configfile) def settingsMap(self, section): dict1 = {} options = self.this_parser.options(section) for option in options: try: dict1[option] = self.this_parser.get(section, option) if dict1[option] == -1: DebugPrint("skip: %s" % option) except: print("exception on %s!" % option) dict1[option] = None return dict1
class Config(Log): _title= 'cfg' _config = None _configdir = expanduser("~/.ads") _configfile = None _schema = None def __init__(self, filename, schema=None): Log.__init__(self, self._title) self._config = SafeConfigParser() if not isdir(self._configdir): self._logger.info(u"creating configuration directory %s" % self._configdir) makedirs(self._configdir) self._configfile = join(self._configdir, filename) self._schema = schema self.load() def configdir(self): return self._configdir def load(self): self._logger.info(u"loading configuration from %s" % self._configfile) self._config.read(self._configfile) def save(self): self._logger.info(u"saving configuration to %s" % self._configfile) self._config.write(open(self._configfile,'wb')) def set(self, section, option, value): if self._schema: _section = u"%s-%s" % (self._schema, section) else: _section = section if not self._config.has_section(_section): self._config.add_section(_section) self._config.set(_section, option, unicode(value)) return value def get(self, section, option, default): if self._schema: _section = u"%s-%s" % (self._schema, section) else: _section = section if (not self._config.has_section(_section) or not self._config.has_option(_section, option)): return self.set(section, option, default) return self._config.get(_section, option) def getint(self, section, option, default): return int(self.get(section, option, default)) def getfloat(self, section, option, default): return float(self.get(section, option, default))
def test_base_url(self): tmpfile = NamedTemporaryFile() config = SafeConfigParser() config.add_section("baseurl") config.set("baseurl", "url", "https://www.example.com/foo") config.write(tmpfile) tmpfile.flush() environ["DJANGO_INSTALLER_SETTINGS"] = tmpfile.name env = {} exec(IMPORT_MAGIC, env) self.assertEqual(env.keys(), IMPORTED_GLOBALS + ['ALLOWED_HOSTS']) self.assertEqual(env['ALLOWED_HOSTS'], ("www.example.com",))
def save(self): parser = SafeConfigParser() name = 'profiles\\default.ini' x = 0 for song in self.player.playlist: parser.add_section('song' + str(x)) parser.set('song' + str(x), 'path', str(song.path)) parser.set('song' + str(x), 'thumb_path', str(song.thumb_path)) parser.set('song' + str(x), 'start_time', str(song.start_time)) parser.set('song' + str(x), 'end_time', str(song.end_time)) parser.set('song' + str(x), 'title', str(song.title)) x += 1 with open(name, 'w') as f: parser.write(f)
def save_to_dot_config(self): filename = os.path.expanduser('~/.osccaprc') parser = SafeConfigParser() fd = open(filename, 'r') parser.readfp(fd) try: parser.add_section('global') except configparser.DuplicateSectionError: pass parser.set('global', 'last_active_name', str(self.active_scope_name)) fd = open(filename + '~', 'w') parser.write(fd) os.rename(filename + '~', filename)
def _update_vnc_api_ini(self, insecure=True): config = SafeConfigParser() config.read(_VNC_API_LIB_INI_) try: config.add_section('global') except DuplicateSectionError: pass config.set('global', 'insecure', str(insecure)) try: config.add_section('auth') except DuplicateSectionError: pass config.set('auth', 'insecure', str(insecure)) with open(_VNC_API_LIB_INI_, 'w') as fd: config.write(fd)
def writeLoginInfo(username, password, acceptNone=False): parser = SafeConfigParser() parser.add_section('Login Info') if username or acceptNone: parser.set('Login Info', 'username', username) if password or acceptNone: parser.set('Login Info', 'password', password) cfg = os.path.join(currentDir(), 'pypcpp.conf') with open(cfg, 'w') as fh: parser.write(fh) # delete session file sess_file = os.path.join(currentDir(), 'sess.pkl') if os.path.isfile(sess_file): os.remove(sess_file)
def write_config(filename, title, artist, tracklist, year, month, day, cover): cfg = SafeConfigParser() cfg.add_section(b) cfg.set(b, 'title', title) cfg.set(b, 'artist', artist) cfg.set(b, 'tracklist', tracklist) cfg.set(b, 'year', year) cfg.set(b, 'month', month) cfg.set(b, 'day', day) cfg.set(b, 'cover', cover) with open(filename, 'w') as f: cfg.write(f)
class Config(object): def __init__(self): self._configFileName = "rover.cfg" self._readConfig() def _readConfig(self): self._config = SafeConfigParser({ "db_host": "localhost", "db_port": "27017", "db_name": "rover", "serial_path": "/dev/ttymxc3", "serial_baud": "115200", "serial_timeout": "0.5", "serial_encoding": "windows-1252"}) self._config.read(self._configFileName) self._validateConfig() def _writeConfig(self): self._config.write(open(self._configFileName, "w")) def _validateConfig(self): changed = False if not self._config.has_section("db"): self._config.add_section("db") changed = True if not self._config.has_section("arduino_serial"): self._config.add_section("arduino_serial") changed = True if changed: self._writeConfig() def get(self, section, key): return self._config.get(section, key) def getInt(self, section, key): return self._config.getint(section, key) def getFloat(self, section, key): return self._config.getfloat(section, key) def getBoolean(self, section, key): return self._config.getboolean(section, key) def set(self, section, key, value): self._config.set(section, key, value) self._writeConfig()
def save(self,savebutton): """Saves fields to a new backup cfg file and repopulates liststore""" self.mode = 'saving' self.getreadybackup() # Reestablish in case changed between polling loops cfgfile = open(self.jobspath+self.readybackup['name']+".ini",'w') parser = SafeConfigParser() parser.add_section('directories') parser.add_section('options') parser.set('directories','source',self.readybackup['source']) parser.set('directories','destination',self.readybackup['dest']) parser.set('options','options',self.readybackup['options']) parser.set('options','sudo',str(self.readybackup['sudo'])) parser.write(cfgfile) cfgfile.close() self.liststore.clear() self.populatelist() self.mode = 'normal'
class GitConfigParser(): section = 'gitcc' def __init__(self): self.file = join(GIT_DIR, '.git', 'gitcc') self.parser = SafeConfigParser(); self.parser.add_section(self.section) def set(self, name, value): self.parser.set(self.section, name, value) def read(self): self.parser.read(self.file) def write(self): self.parser.write(open(self.file, 'w')) def get(self, name, default=None): if not self.parser.has_option(self.section, name): return default return self.parser.get(self.section, name) def getList(self, name, default=None): return self.get(name, default).split('|')
def config_save(): cfg = get_config() config = SafeConfigParser() config.read(cfg) if not config.has_section('path'): config.add_section('path') config.set('path', 'path', basePath) config.set('path', 'rootfolder', arcRoot) config.set('path', 'dbfolder', db_folder) config.set('path', 'dbname', db_name) config.set('path', 'downloadfolder', dl_folder) with open(cfg, 'w') as f: config.write(f)
def saveGamepad(_settings): parser = SafeConfigParser() for controller_name in getSetting().getGamepadList(): gamepad = getSetting(controller_name) if not parser.has_section(controller_name): parser.add_section(controller_name) for key,value in gamepad.key_bindings.axis_bindings.iteritems(): neg,pos = value if not neg: neg = 'none' if not pos: pos = 'none' parser.set(controller_name,'a'+str(key),'('+str(neg)+','+str(pos)+')' ) for key,value in gamepad.key_bindings.button_bindings.iteritems(): parser.set(controller_name,'b'+str(key),str(value)) with open(os.path.join(getSetting().datadir.replace('main.exe',''),'settings','gamepads.ini'), 'w') as configfile: parser.write(configfile)
class Configuration(object): def __init__(self): self.parser = SafeConfigParser(defaults={ 'theme' : 'default', 'theme.mobile' : 'touch', 'hostname' : '0.0.0.0', 'port' : '7000', 'log.file' : '/tmp/rb-serve.log', 'log.level' : 'INFO', 'log.format' : '%(levelname)s %(asctime)s %(name)s: %(message)s', 'debug' : 'False', }) self.parser.add_section('server') self.parser.read(path.expanduser('~/.rhythmweb')) self.configure_logger() def get_string(self, key): return self.parser.get('server', key, raw=True) def get_int(self, key): return self.parser.getint('server', key) def get_boolean(self, key): return self.parser.getboolean('server', key) def configure_logger(self): root = logging.getLogger() root.setLevel(self.get_string('log.level')) handler = logging.handlers.RotatingFileHandler( self.get_string('log.file'), backupCount=5, maxBytes=1024*1024) handler.setFormatter(logging.Formatter(fmt=self.get_string('log.format'))) root.addHandler(handler) if root.isEnabledFor(logging.DEBUG): root.debug('Logger configured') root.debug('Showing app configuration:') for section_name in self.parser.sections(): root.debug('Section: %s' % section_name) for key in self.parser.options(section_name): root.debug(' %s = %s' % (key, self.parser.get(section_name, key, raw=True)))
def _load(self, location): """ location -- URL or file location isxsd -- is this a xsd file? """ cachedir = self._cachedir # wsdl2py: deal with XML Schema if not os.path.isdir(cachedir): os.mkdir(cachedir) _file = os.path.join(cachedir, '.cache') section = 'TYPES' cp = ConfigParser() try: cp.readfp(open(_file, 'r')) except IOError: del cp; cp = None option = location.replace(':', '-') # colons seem to screw up option if (not self._force and cp is not None and cp.has_section(section) and cp.has_option(section, option)): types = cp.get(section, option) else: # dont do anything to anames if not self._pyclass: containers.ContainerBase.func_aname = lambda instnc,n: str(n) args = ['-o', cachedir, location] if self._lazy: args.insert(0, '-l') if self._pyclass: args.insert(0, '-b') files = commands.wsdl2py(args) if cp is None: cp = ConfigParser() if not cp.has_section(section): cp.add_section(section) types = [f for f in files if f.endswith('_types.py')][0] cp.set(section, option, types) cp.write(open(_file, 'w')) if os.path.abspath(cachedir) not in sys.path: sys.path.append(os.path.abspath(cachedir)) mod = os.path.split(types)[-1].rstrip('.py') return __import__(mod)
def saveIniAndDestroy (self): """Writes current information to the ini file (wormBait.ini) and closes the user interface""" config = SafeConfigParser() config.read('wormBait.ini') if not config.has_section('wormBait'): config.add_section('wormBait') dbIds = self.entryList.getValue() if '\n' in dbIds: dbIds = ','.join(dbIds.strip().split('\n')) config.set('wormBait', 'dbIds', dbIds) config.set('wormBait', 'degFile', self.dbFilePath.get()) config.set('wormBait', 'outFile', self.outFilePath.get()) with open('wormBait.ini', 'w') as f: config.write(f) self.destroy()
def save(cls): config = SafeConfigParser() # Make option section config.add_section('options') for key, value in cls.config.iteritems(): config.set('options', str(key), unicode(value)) # Make the series sections for name, title, path, TVDBID, lang in cls.series: name = str(name) config.add_section(name) config.set(name, 'title', unicode(title)) config.set(name, 'theTvDb', str(TVDBID)) config.set(name, 'videos', unicode(path)) config.set(name, 'lang', unicode(lang)) # Write the config with codecs.open(CONFIG_FILE, 'w+', encoding='utf-8') as f: config.write(f)