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 generate_service_config(self): upstream_config = RawConfigParser(dict_type=M) upstream_config.optionxform = str upstream_config.add_section('Unit') upstream_config.set('Unit', 'Description', self.description) setup_timer = ( 'idle-timeout' in self.config['controller'] and not (self.config['controller']['idle-timeout'] == 'infinity')) if setup_timer: upstream_config.set('Unit', 'Requires', 'idle.timer') upstream_config.set('Unit', 'After', 'idle.timer') upstream_config.add_section('Service') upstream_config.set( 'Service', 'ExecStart', '%s %s %s %s %s %s' % (self.start_command, self.project, self.name, self.upstream_socket, self.service, " ".join(self.services))) if self.wait_command: upstream_config.set( 'Service', 'ExecStartPost', "%s %s %s %s %s" % (self.wait_command, self.project, self.name, self.upstream_socket, self.service)) if self.stop_command: upstream_config.set( 'Service', 'ExecStop', '%s %s %s %s %s' % (self.stop_command, self.project, self.name, self.upstream_socket, self.service)) if self.private_tmp: upstream_config.set('Service', 'PrivateTmp', 'true') for env_var in self.env_vars: upstream_config.set('Service', 'Environment', env_var) if self.remain_after_exit: upstream_config.set('Service', 'RemainAfterExit', 'true') upstream_config.write( open('/etc/haproxy/system/%s.service' % self.ctrl_name, 'w'))
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 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 store_api_key(npr_API_key): """ Stores a candidate NPR API key into the configuration file, ``~/.config/nprstuff/nprstuff.conf``, into the ``NPR_DATA`` section and ``apikey`` key. :param str npr_API_key: candidate NPR API key. .. seealso:: :py:meth:`get_api_key <nprstuff.core.npr_utils.get_api_key>`. """ resource = 'nprstuff' filename = '%s.conf' % resource baseConfDir = os.path.abspath(os.path.expanduser('~/.config/%s' % resource)) absPath = os.path.join(baseConfDir, filename) if os.path.isdir(absPath): shutil.rmtree(absPath) if not os.path.isfile(absPath): cparser = RawConfigParser() else: cparser = ConfigParser() cparser.read(absPath) # if 'NPR_DATA' not in cparser.sections(): cparser.add_section('NPR_DATA') cparser.set('NPR_DATA', 'apikey', npr_API_key) with open(absPath, 'w') as openfile: cparser.write(openfile) os.chmod(absPath, 0o600)
def _save_config_file(self, config): """Write config to disk. """ # Generate a sanitized version of our running configuration sane_config = RawConfigParser() for section_name, section in config.items(): sane_config.add_section(section_name) for option_name, value in section.items(): if self.config_source[section_name][ option_name] == 'config_file' and value is not None: sane_config.set(section_name, option_name, str(value)) if not self.config_dir.exists(): self.config_dir.mkdir(parents=True, exist_ok=True) # Write the config file atomically. self.acquire_lock() with NamedTemporaryFile(mode='w', dir=str(self.config_dir), delete=False) as tmpfile: sane_config.write(tmpfile) if os.path.getsize(tmpfile.name) > 0: os.replace(tmpfile.name, str(self.config_file)) else: self.log.warning( 'Config file saving failed, not replacing %s with %s.', str(self.config_file), tmpfile.name) self.release_lock()
def test_push_inits_no_stdout_spam(): # git init has a tendency to spew to stdout, and that confuses # e.g. a git push tmp = util.maketemp() cfg = RawConfigParser() cfg.add_section('gitosis') repositories = os.path.join(tmp, 'repositories') os.mkdir(repositories) cfg.set('gitosis', 'repositories', repositories) generated = os.path.join(tmp, 'generated') os.mkdir(generated) cfg.set('gitosis', 'generate-files-in', generated) cfg.add_section('group foo') cfg.set('group foo', 'members', 'jdoe') cfg.set('group foo', 'writable', 'foo') old_stdout = os.dup(1) try: new_stdout = os.tmpfile() os.dup2(new_stdout.fileno(), 1) serve.serve( cfg=cfg, user='******', command="git-receive-pack 'foo'", ) finally: os.dup2(old_stdout, 1) os.close(old_stdout) new_stdout.seek(0) got = new_stdout.read() new_stdout.close() eq(got, '') eq(os.listdir(repositories), ['foo.git']) assert os.path.isfile(os.path.join(repositories, 'foo.git', 'HEAD'))
def save_jwt_token(token, expiration=None, path=None): """ Saves JWT token in the config file. """ # Default to ~/.htrc if path is None: path = DEFAULT_PATH # Default to expiration of now - force a new token on next request if expiration is None: expiration = time.time() # Open and modify existing config file, if it exists. config = ConfigParser(allow_no_value=True) if os.path.exists(path): config.read(path) if not config.has_section('jwt'): config.add_section('jwt') # set token and expiration config.set('jwt', 'token', token) config.set('jwt', 'expiration', expiration) with open(path, 'w') as credential_file: config.write(credential_file) return token
def setUp(self): self.tempdir = tempfile.mkdtemp('attachtest', 'fuglu') self.template = '%s/blockedfile.tmpl' % self.tempdir shutil.copy( CONFDIR + '/templates/blockedfile.tmpl.dist', self.template) shutil.copy(CONFDIR + '/rules/default-filenames.conf.dist', '%s/default-filenames.conf' % self.tempdir) shutil.copy(CONFDIR + '/rules/default-filetypes.conf.dist', '%s/default-filetypes.conf' % self.tempdir) config = RawConfigParser() config.add_section('FiletypePlugin') config.set('FiletypePlugin', 'template_blockedfile', self.template) config.set('FiletypePlugin', 'rulesdir', self.tempdir) config.set('FiletypePlugin', 'blockaction', 'DELETE') config.set('FiletypePlugin', 'sendbounce', 'True') config.set('FiletypePlugin', 'checkarchivenames', 'True') config.set('FiletypePlugin', 'checkarchivecontent', 'True') config.set('FiletypePlugin', 'archivecontentmaxsize', '5000000') config.set('FiletypePlugin', 'enabledarchivetypes', '') config.add_section('main') config.set('main', 'disablebounces', '1') self.candidate = FiletypePlugin(config) self.rulescache = RulesCache(self.tempdir) self.candidate.rulescache = self.rulescache
def write(self, config_data, filepath=None): """ Create a dotfile from keyword arguments. :param config_data: Dict of config settings :param filepath: (Optional) Path to write """ if filepath is None: filepath = self.filepath config = RawConfigParser() section = constants.SECTION_NAME config.add_section(section) # Set the config settings for key, val in six.iteritems(config_data): config.set(section, key, val) with open(filepath, 'w') as dotfile: config.write(dotfile) self.enforce_perms() log.debug('wrote %s' % filepath)
def init_admin_repository( git_dir, pubkey, user, ): repository.init(path=git_dir, template=resource_filename('gitosis.templates', 'admin')) repository.init(path=git_dir, ) # can't rely on setuptools and all kinds of distro packaging to # have kept our templates executable, it seems os.chmod(os.path.join(git_dir, 'hooks', 'post-update'), 0o755) if not repository.has_initial_commit(git_dir): log.info('Making initial commit...') # ConfigParser does not guarantee order, so jump through hoops # to make sure [gitosis] is first cfg_file = StringIO() print('[gitosis]', file=cfg_file) #print('', end="", file=cfg_file) #print >>cfg_file, '[gitosis]' #print >>cfg_file cfg = RawConfigParser() cfg.add_section('group gitosis-admin') cfg.set('group gitosis-admin', 'members', user) cfg.set('group gitosis-admin', 'writable', 'gitosis-admin') cfg.write(cfg_file) initial_commit( git_dir=git_dir, cfg=cfg_file.getvalue(), pubkey=pubkey, user=user, )
def setUp(self): self.tempfiles = [] config = RawConfigParser() config.add_section('main') config.set('main', 'disablebounces', '1') config.add_section('ArchivePlugin') config.set('ArchivePlugin', 'archivedir', '/tmp') config.set('ArchivePlugin', 'subdirtemplate', '') config.set('ArchivePlugin', 'filenametemplate', '${id}.eml') config.set('ArchivePlugin', 'storeoriginal', '1') config.set('ArchivePlugin', 'chmod', '700') config.set('ArchivePlugin', 'chown', '') config.set('ArchivePlugin', 'chgrp', '') tempfilename = tempfile.mktemp(suffix='archive', prefix='fuglu-unittest', dir='/tmp') fp = open(tempfilename, 'w') fp.write('From unittests.fuglu.org') self.tempfiles.append(tempfilename) config.set('ArchivePlugin', 'archiverules', tempfilename) self.config = config
def store_waitwait_downloaddir(waitwait_downloaddir): """ Stores the default location of the `NPR Fresh Air`_ episodes into the configuration file, ``~/.config/nprstuff/nprstuff.com``, into the ``NPR_DATA`` section and ``waitwait_downloaddir`` key. :param str waitwait_downloaddir: the default directory to download `NPR Fresh Air`_ episodes. .. seealso:: :py:meth:`get_waitwait_downloaddir <nprstuff.core.npr_utils.get_waitwait_downloaddir>`. """ assert (os.path.isdir(os.path.abspath(waitwait_downloaddir))) resource = 'nprstuff' filename = '%s.conf' % resource baseConfDir = os.path.abspath(os.path.expanduser('~/.config/%s' % resource)) absPath = os.path.join(baseConfDir, filename) if os.path.isdir(absPath): shutil.rmtree(absPath) if not os.path.isfile(absPath): cparser = RawConfigParser() else: cparser = ConfigParser() cparser.read(absPath) if 'NPR_DATA' not in cparser.sections(): cparser.add_section('NPR_DATA') cparser.set('NPR_DATA', 'waitwait_downloaddir', os.path.abspath(waitwait_downloaddir)) with open(absPath, 'w') as openfile: cparser.write(openfile) os.chmod(absPath, 0o600)
def test_push_inits_subdir_parent_exists(): tmp = util.maketemp() cfg = RawConfigParser() cfg.add_section('gitosis') repositories = os.path.join(tmp, 'repositories') os.mkdir(repositories) foo = os.path.join(repositories, 'foo') # silly mode on purpose; not to be touched os.mkdir(foo, 0o751) cfg.set('gitosis', 'repositories', repositories) generated = os.path.join(tmp, 'generated') os.mkdir(generated) cfg.set('gitosis', 'generate-files-in', generated) cfg.add_section('group foo') cfg.set('group foo', 'members', 'jdoe') cfg.set('group foo', 'writable', 'foo/bar') serve.serve( cfg=cfg, user='******', command="git-receive-pack 'foo/bar.git'", ) eq(os.listdir(repositories), ['foo']) util.check_mode(foo, 0o751, is_dir=True) eq(os.listdir(foo), ['bar.git']) assert os.path.isfile(os.path.join(repositories, 'foo', 'bar.git', 'HEAD'))
def test_typo_writeable(): tmp = util.maketemp() repository.init(os.path.join(tmp, 'foo.git')) cfg = RawConfigParser() cfg.add_section('gitosis') cfg.set('gitosis', 'repositories', tmp) cfg.add_section('group foo') cfg.set('group foo', 'members', 'jdoe') cfg.set('group foo', 'writeable', 'foo') log = logging.getLogger('gitosis.serve') buf = StringIO() handler = logging.StreamHandler(buf) log.addHandler(handler) try: got = serve.serve( cfg=cfg, user='******', command="git-receive-pack 'foo'", ) finally: log.removeHandler(handler) eq(got, "git-receive-pack '%s/foo.git'" % tmp) handler.flush() eq( buf.getvalue(), "Repository 'foo' config has typo \"writeable\", shou" + "ld be \"writable\"\n", )
def test_no_notListed(): cfg = RawConfigParser() cfg.add_section('group hackers') cfg.set('group hackers', 'members', 'wsmith') gen = group.getMembership(config=cfg, user='******') eq(gen.next(), 'all') assert_raises(StopIteration, gen.next)
class LogConsumerConfig(object): def __init__(self, filename): self.__config = RawConfigParser() if not os.path.exists(filename): f = io.open(filename, 'wb') self.__init_config() self.__config.write(f) f.close() self.__config.read(filename) def __init_config(self): #add section self.__config.add_section(LogConsumerSections.kafka) self.__config.add_section(LogConsumerSections.mysql) #set kafka section default value self.__config.set(LogConsumerSections.kafka, LogConsumerOptions.hosts, 'localhost:9092') self.__config.set(LogConsumerSections.kafka,LogConsumerOptions.topics, 'test1') self.__config.set(LogConsumerSections.kafka,LogConsumerOptions.consumer_group, 'test') self.__config.set(LogConsumerSections.kafka,LogConsumerOptions.auto_commit_interval_ms, '1') self.__config.set(LogConsumerSections.kafka,LogConsumerOptions.consumer_id, 'test') self.__config.set(LogConsumerSections.kafka,LogConsumerOptions.partition_offset, '-1') #set mysql section default value self.__config.set(LogConsumerSections.mysql,LogConsumerOptions.commit_batch, '100') self.__config.set(LogConsumerSections.mysql,LogConsumerOptions.hosts, 'localhost') self.__config.set(LogConsumerSections.mysql, LogConsumerOptions.port, '3306') self.__config.set(LogConsumerSections.mysql, LogConsumerOptions.user, 'root') self.__config.set(LogConsumerSections.mysql, LogConsumerOptions.password, '666666') def config(self): return self.__config
def test_imap_config_values_should_be_stored(): am = AccountManager() option_spec = get_mailbox_parameter_specs('imap') options = { 'user': '******', 'password': '', 'server': 'imap.example.org', 'port': '', 'ssl': True, 'imap': True, 'idle': True, 'folders': ['a', 'b'], } config = RawConfigParser() config.add_section('account1') am._set_cfg_options(config, 'account1', options, option_spec) expected_config_items = [ ('user', 'you'), ('password', ''), ('server', 'imap.example.org'), ('port', ''), ('ssl', '1'), ('imap', '1'), ('idle', '1'), ('folder', '["a", "b"]'), ] assert set(expected_config_items) == set(config.items('account1'))
def create(self, contact, duedelta: Optional[int] = None, **kwargs): if duedelta is None: duedelta = self.default_due with self.lock: today = datetime.date.today() due = today + datetime.timedelta(days=duedelta) filename = self.find_filename() invoice = RawConfigParser() invoice.add_section("invoice") invoice.set("invoice", "contact", contact) invoice.set("invoice", "date", today.isoformat()) invoice.set("invoice", "due", due.isoformat()) # Apply defaults from contact contact = self.read_contact(contact) for key, value in contact.items(): if not key.startswith("default_"): continue invoice.set("invoice", key[8:], value) # Apply passed value for key, value in kwargs.items(): invoice.set("invoice", key, value) # Ensure rate and item are present for key in ("rate", "item"): if not invoice.has_option("invoice", key): invoice.set("invoice", key, "") # Store the file self.ensure_dir(filename) with open(filename, "w") as handle: invoice.write(handle) return filename
def _config(self): config = RawConfigParser() config.add_section('gtimelog') config.set('gtimelog', 'list-email', self.email) config.set('gtimelog', 'name', self.name) config.set('gtimelog', 'sender', self.sender) config.set('gtimelog', 'editor', self.editor) config.set('gtimelog', 'mailer', self.mailer) config.set('gtimelog', 'spreadsheet', self.spreadsheet) config.set('gtimelog', 'chronological', str(self.chronological)) config.set('gtimelog', 'summary_view', str(self.summary_view)) config.set('gtimelog', 'show_tasks', str(self.show_tasks)) config.set('gtimelog', 'gtk-completion', str(self.enable_gtk_completion)) config.set('gtimelog', 'hours', str(self.hours)) config.set('gtimelog', 'office-hours', str(self.office_hours)) config.set('gtimelog', 'virtual_midnight', self.virtual_midnight.strftime('%H:%M')) config.set('gtimelog', 'task_list_url', self.task_list_url) config.set('gtimelog', 'edit_task_list_cmd', self.edit_task_list_cmd) config.set('gtimelog', 'show_office_hours', str(self.show_office_hours)) config.set('gtimelog', 'show_tray_icon', str(self.show_tray_icon)) config.set('gtimelog', 'prefer_app_indicator', str(self.prefer_app_indicator)) config.set('gtimelog', 'report_style', str(self.report_style)) config.set('gtimelog', 'start_in_tray', str(self.start_in_tray)) return config
def _save_config(self): """Save configuration options.""" cfg = RawConfigParser() cfg.read([config.config_path]) if not cfg.has_section("ui"): cfg.add_section("ui") cfg.set("ui", "browse_dir", self._browse_dir) cfg.set("ui", "enable_downscaling", str(self.viewer.enable_downscaling.get())) cfg.set("ui", "rename_and_move_dir", self._rename_and_move_dir) try: # Make a folder for the configuration file if needed config_dir = os.path.dirname(config.config_path) if not os.path.isdir(config_dir): os.makedirs(config_dir) # Save the configuration file with open(config.config_path, "w") as config_file: cfg.write(config_file) except (Exception): # The worst case here is we can't save the configuration file pass
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'
class TestGithubService(TestCase): def setUp(self): self.config = RawConfigParser() self.config.interactive = False self.config.add_section('general') self.config.add_section('mygithub') self.config.set('mygithub', 'service', 'github') self.config.set('mygithub', 'github.login', 'tintin') self.config.set('mygithub', 'github.username', 'milou') self.config.set('mygithub', 'github.password', 't0ps3cr3t') self.service_config = ServiceConfig(GithubService.CONFIG_PREFIX, self.config, 'mygithub') def test_token_authorization_header(self): self.config.remove_option('mygithub', 'github.password') self.config.set('mygithub', 'github.token', '@oracle:eval:echo 1234567890ABCDEF') service = GithubService(self.config, 'general', 'mygithub') self.assertEqual(service.client.session.headers['Authorization'], "token 1234567890ABCDEF") def test_default_host(self): """ Check that if github.host is not set, we default to github.com """ service = GithubService(self.config, 'general', 'mygithub') self.assertEquals("github.com", service.host) def test_overwrite_host(self): """ Check that if github.host is set, we use its value as host """ self.config.set('mygithub', 'github.host', 'github.example.com') service = GithubService(self.config, 'general', 'mygithub') self.assertEquals("github.example.com", service.host) def test_keyring_service(self): """ Checks that the keyring service name """ keyring_service = GithubService.get_keyring_service( self.service_config) self.assertEquals("github://[email protected]/milou", keyring_service) def test_keyring_service_host(self): """ Checks that the keyring key depends on the github host. """ self.config.set('mygithub', 'github.host', 'github.example.com') keyring_service = GithubService.get_keyring_service( self.service_config) self.assertEquals("github://[email protected]/milou", keyring_service) def test_get_repository_from_issue_url__issue(self): issue = dict(repos_url="https://github.com/foo/bar") repository = GithubService.get_repository_from_issue(issue) self.assertEquals("foo/bar", repository) def test_get_repository_from_issue_url__pull_request(self): issue = dict(repos_url="https://github.com/foo/bar") repository = GithubService.get_repository_from_issue(issue) self.assertEquals("foo/bar", repository) def test_get_repository_from_issue__enterprise_github(self): issue = dict(repos_url="https://github.acme.biz/foo/bar") repository = GithubService.get_repository_from_issue(issue) self.assertEquals("foo/bar", repository)
def saveConfigini(): parser = RawConfigParser() parser.add_section('GPORTAL') for key in configini.keys(): parser.set('GPORTAL', key, configini[key]) with open('scumlogs.ini', 'w', encoding="utf-8") as f: parser.write(f)
def setUp(self): self.tempfiles = [] config = RawConfigParser() config.add_section('main') config.set('main', 'disablebounces', '1') config.add_section('ArchivePlugin') config.set('ArchivePlugin', 'archivedir', '/tmp') config.set('ArchivePlugin', 'subdirtemplate', '') config.set('ArchivePlugin', 'filenametemplate', '${id}.eml') config.set('ArchivePlugin', 'storeoriginal', '1') config.set('ArchivePlugin', 'chmod', '700') config.set('ArchivePlugin', 'chown', '') config.set('ArchivePlugin', 'chgrp', '') tempfilename = tempfile.mktemp( suffix='archive', prefix='fuglu-unittest', dir='/tmp') fp = open(tempfilename, 'w') fp.write('From unittests.fuglu.org') self.tempfiles.append(tempfilename) config.set('ArchivePlugin', 'archiverules', tempfilename) self.config = config
def _read_from_sections(user, collection_url, permission): regex = ConfigParser({'login': user, 'path': collection_url}) for rights in (INITIAL_RIGHTS, settings.DJRADICALE_RIGHTS): for section, values in rights.items(): if not regex.has_section(section): regex.add_section(section) for key, value in values.items(): regex.set( section, key, value % { 'login': re.escape(user), 'path': re.escape(collection_url), }) log.LOGGER.debug("Rights type '%s'" % __name__) for section in regex.sections(): re_user = regex.get(section, 'user') re_collection = regex.get(section, 'collection') log.LOGGER.debug( "Test if '%s:%s' matches against '%s:%s' from section '%s'" % ( user, collection_url, re_user, re_collection, section)) user_match = re.match(re_user, user) if user_match: re_collection = re_collection.format(*user_match.groups()) if re.match(re_collection, collection_url): log.LOGGER.debug("Section '%s' matches" % section) if permission in regex.get(section, 'permission'): return True else: log.LOGGER.debug("Section '%s' does not match" % section) return False
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)
class Config(object): def __init__(self, file='config.ini'): super().__init__() self.file = file self.config = RawConfigParser() self.config.read(self.file, encoding='utf-8') # 读取文件 def getConfig(self, section, option): ''' 读取config.ini配置文件 ''' try: return self.config.get(section, option) except: return None def saveConfig(self, section, option, value=None): ''' 保存config.ini配置文件 ''' try: self.config.add_section(section) # 如果键值不存在,则创建键值 except: pass self.config.set(section, option, value) self.config.write(open(self.file, "w+", encoding='utf-8')) # 写入文件(读写模式)
def _init_config_parser(): """ Creates the RawConfigParser object, adds the fields and fills with default/empty values :return: """ global _conf_parser # Create a new config parser _conf_parser = RawConfigParser() # Put all options under a Settings Header _conf_parser.add_section("Settings") # Create defaults tuple SettingsDefault = namedtuple('SettingsDefault', ['setting', 'default_value']) default_settings = [ SettingsDefault._make(["client_id", ""]), SettingsDefault._make(["client_secret", ""]), SettingsDefault._make(["username", ""]), SettingsDefault._make(["password", ""]), SettingsDefault._make(["base_url", ""]), SettingsDefault._make(["parser", "directory"]), SettingsDefault._make(["readonly", False]), SettingsDefault._make(["delay", 0]), SettingsDefault._make( ["timeout", 10]), # default timeout scale is 10 seconds per mb SettingsDefault._make(["minimum_file_size", 0]) ] # default minimum file size in kb # add defaults to config parser for config in default_settings: _conf_parser.set("Settings", config.setting, config.default_value)
class ConfigHandler: def __init__(self, file_name): self.conf = RawConfigParser() self.file_name = os.path.join(conf_loc, file_name) self.conf.read(self.file_name, encoding='utf-8') def get_sections(self): """获取所有的sections""" return self.conf.sections() def get_options(self, section): """获取section下所有的option""" return self.conf.options(section) def read(self, section, option): """读取section,下option的值""" return self.conf.get(section, option) def write(self, section, option, value): """1、判断该片段是否存在,不存在新增加一个节点 2、该节点存在的话,如果键存在,更新值 3、键不存在,新增一个键,并为其赋值 """ if not self.conf.has_section(section): self.conf.add_section(section) self.conf.set(section, option, value) with open(self.file_name, 'w', encoding='utf-8') as f: self.conf.write(f) def return_data(self, section, option): """将查询到的数据范围为原类型""" result = self.read(section, option) return eval(result)
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)
def _config(self): config = RawConfigParser() config.add_section('gtimelog') config.set('gtimelog', 'list-email', self.email) config.set('gtimelog', 'name', self.from_unicode(self.name)) config.set('gtimelog', 'sender', self.from_unicode(self.sender)) config.set('gtimelog', 'editor', self.editor) config.set('gtimelog', 'mailer', self.mailer) config.set('gtimelog', 'spreadsheet', self.spreadsheet) config.set('gtimelog', 'chronological', str(self.chronological)) config.set('gtimelog', 'summary_view', str(self.summary_view)) config.set('gtimelog', 'show_tasks', str(self.show_tasks)) config.set('gtimelog', 'gtk-completion', str(self.enable_gtk_completion)) config.set('gtimelog', 'hours', str(self.hours)) config.set('gtimelog', 'office-hours', str(self.office_hours)) config.set('gtimelog', 'virtual_midnight', self.virtual_midnight.strftime('%H:%M')) config.set('gtimelog', 'task_list_url', self.task_list_url) config.set('gtimelog', 'edit_task_list_cmd', self.edit_task_list_cmd) config.set('gtimelog', 'show_office_hours', str(self.show_office_hours)) config.set('gtimelog', 'show_tray_icon', str(self.show_tray_icon)) config.set('gtimelog', 'prefer_app_indicator', str(self.prefer_app_indicator)) config.set('gtimelog', 'report_style', str(self.report_style)) config.set('gtimelog', 'start_in_tray', str(self.start_in_tray)) return config
def create_storage_account(storagename, resource_group_name, location_storage='westeurope', sku='Standard_LRS', storage_kind='StorageV2', config_name='default', saveconfig=True): file_path = os.path.join(os.getcwd(), 'batch_files\create_storage_account.bat') os.system("C:\Windows\System32\cmd.exe /c " + file_path + ' ' + storagename + ' ' + resource_group_name + ' ' + location_storage + ' ' + sku + ' ' + storage_kind) if saveconfig == True: if not os.path.exists("config"): os.mkdir("config") print( "Saving Configuration to config/blob.ini \n Please Keep This File Secure." ) config = RawConfigParser() config.read('config/blob.ini') config.add_section(config_name) config.set(config_name, 'storagename', storagename) config.set(config_name, 'resource_group_name', resource_group_name) config.set(config_name, 'location_storage', location_storage) config.set(config_name, 'sku', sku) config.set(config_name, 'storage_kind', storage_kind) with open('config/blob.ini', 'w') as f: config.write(f)
def setUp(self): self.tempdir = tempfile.mkdtemp('attachtest', 'fuglu') self.template = '%s/blockedfile.tmpl' % self.tempdir shutil.copy( CONFDIR + '/templates/blockedfile.tmpl.dist', self.template) shutil.copy(CONFDIR + '/rules/default-filenames.conf.dist', '%s/default-filenames.conf' % self.tempdir) shutil.copy(CONFDIR + '/rules/default-filetypes.conf.dist', '%s/default-filetypes.conf' % self.tempdir) config = RawConfigParser() config.add_section('FiletypePlugin') config.set('FiletypePlugin', 'template_blockedfile', self.template) config.set('FiletypePlugin', 'rulesdir', self.tempdir) config.set('FiletypePlugin', 'blockaction', 'DELETE') config.set('FiletypePlugin', 'sendbounce', 'True') config.set('FiletypePlugin', 'checkarchivenames', 'True') config.set('FiletypePlugin', 'checkarchivecontent', 'True') config.set('FiletypePlugin', 'archivecontentmaxsize', '7000000') config.set('FiletypePlugin', 'archiveextractlevel', -1) config.set('FiletypePlugin', 'enabledarchivetypes', '') config.add_section('main') config.set('main', 'disablebounces', '1') self.candidate = FiletypePlugin(config) self.rulescache = RulesCache(self.tempdir) self.candidate.rulescache = self.rulescache
def save_connection_config(self) -> None: if self.name and self.url: config_parser = RawConfigParser() config_parser.add_section(SECTION_TITLE) config_parser.set(SECTION_TITLE, 'url', self.url) if self._requires_auth: config_parser.set(SECTION_TITLE, 'username', self._auth['username']) password = encode(encode_password(), self._auth['password']) config_parser.set(SECTION_TITLE, 'password', password) if self.jenkins_views: config_parser.set(SECTION_TITLE, 'views', ','.join(self.view_names)) for view in self.views: view.save_view_config() save_argus_config( config_parser, build_config_file(jenkins_connections_dir, self.name)) else: raise ConfigError( 'No data to save in JenkinsConnection config file.')
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_sts_token(self, profile, access_key_id, secret_access_key, session_token): """ Writes STS auth information to credentials file """ region = 'us-east-1' output = 'json' if not os.path.exists(self.creds_dir): os.makedirs(self.creds_dir) config = RawConfigParser() if os.path.isfile(self.creds_file): config.read(self.creds_file) if not config.has_section(profile): config.add_section(profile) config.set(profile, 'output', output) config.set(profile, 'region', region) config.set(profile, 'aws_access_key_id', access_key_id) config.set(profile, 'aws_secret_access_key', secret_access_key) config.set(profile, 'aws_session_token', session_token) with open(self.creds_file, 'w+') as configfile: config.write(configfile) self.logger.info("Temporary credentials written to profile: %s" % profile) self.logger.info("Invoke using: aws --profile %s <service> <command>" % profile)
def setUp(self): config = RawConfigParser() config.add_section('main') config.set('main', 'disablebounces', '1') config.add_section('SAPlugin') # current tests don't need config options, add them here later if # necessary self.config = config
class TestGithubService(TestCase): def setUp(self): self.config = RawConfigParser() self.config.interactive = False self.config.add_section('general') self.config.add_section('mygithub') self.config.set('mygithub', 'service', 'github') self.config.set('mygithub', 'github.login', 'tintin') self.config.set('mygithub', 'github.username', 'milou') self.config.set('mygithub', 'github.password', 't0ps3cr3t') self.service_config = ServiceConfig( GithubService.CONFIG_PREFIX, self.config, 'mygithub') def test_token_authorization_header(self): self.config.remove_option('mygithub', 'github.password') self.config.set('mygithub', 'github.token', '@oracle:eval:echo 1234567890ABCDEF') service = GithubService(self.config, 'general', 'mygithub') self.assertEqual(service.client.session.headers['Authorization'], "token 1234567890ABCDEF") def test_default_host(self): """ Check that if github.host is not set, we default to github.com """ service = GithubService(self.config, 'general', 'mygithub') self.assertEquals("github.com", service.host) def test_overwrite_host(self): """ Check that if github.host is set, we use its value as host """ self.config.set('mygithub', 'github.host', 'github.example.com') service = GithubService(self.config, 'general', 'mygithub') self.assertEquals("github.example.com", service.host) def test_keyring_service(self): """ Checks that the keyring service name """ keyring_service = GithubService.get_keyring_service(self.service_config) self.assertEquals("github://[email protected]/milou", keyring_service) def test_keyring_service_host(self): """ Checks that the keyring key depends on the github host. """ self.config.set('mygithub', 'github.host', 'github.example.com') keyring_service = GithubService.get_keyring_service(self.service_config) self.assertEquals("github://[email protected]/milou", keyring_service) def test_get_repository_from_issue_url__issue(self): issue = dict(repos_url="https://github.com/foo/bar") repository = GithubService.get_repository_from_issue(issue) self.assertEquals("foo/bar", repository) def test_get_repository_from_issue_url__pull_request(self): issue = dict(repos_url="https://github.com/foo/bar") repository = GithubService.get_repository_from_issue(issue) self.assertEquals("foo/bar", repository) def test_get_repository_from_issue__enterprise_github(self): issue = dict(repos_url="https://github.acme.biz/foo/bar") repository = GithubService.get_repository_from_issue(issue) self.assertEquals("foo/bar", repository)
def create_spawn_config(self, subsystem_config): """Create config instance """ section_name = self.defaults['pki_subsystem'] cfgtpl, immutable_keys = self._get_default_config() # overwrite CA/KRA config with subsystem settings subsystem_config = self._mangle_values(subsystem_config) for key, value in subsystem_config.items(): cfgtpl.set(section_name, key, value) # get a mapping of settings that cannot be modified by users immutable_settings = { k: v for k, v in cfgtpl.items(section_name) if k in immutable_keys } # add ipaca_customize overlay, # These are settings that can be modified by a user, too. We use # ipaca_customize.ini to set sensible defaults. with open(self.ipaca_customize) as f: cfgtpl.read_file(f) # load external overlay from command line if self.pki_config_override is not None: with open(self.pki_config_override) as f: cfgtpl.read_file(f) # verify again self._verify_immutable( cfgtpl, immutable_settings, self.pki_config_override ) # key backup is not compatible with HSM support if (cfgtpl.has_option(section_name, 'pki_hsm_enable') and cfgtpl.getboolean(section_name, 'pki_hsm_enable')): cfgtpl.set(section_name, 'pki_backup_keys', 'False') cfgtpl.set(section_name, 'pki_backup_password', '') pki_token_name = cfgtpl.get(section_name, 'pki_token_name') for stanza in self.token_stanzas: if cfgtpl.has_option(section_name, stanza): cfgtpl.set(section_name, stanza, pki_token_name) # Next up, get rid of interpolation variables, DEFAULT, # irrelevant sections and unused variables. Only the subsystem # section is copied into a new raw config parser. A raw config # parser is necessary, because ConfigParser.write() write passwords # with '%' in a way, that is not accepted by Dogtag. config = RawConfigParser() config.optionxform = str config.add_section(section_name) for key, value in sorted(cfgtpl.items(section=section_name)): if key.startswith('pki_'): config.set(section_name, key, value) return config
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_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 get_base_env(cls, name, section, options=None, server=None): ''' Get a base environment. ''' options = options or {} parser = RawConfigParser() parser.add_section(section) for option, value in options.items(): parser.set(section, option, value) return cls(name, parser, section, server)
def load(paths=()): config = ConfigParser() for section, values in INITIAL_CONFIG.items(): config.add_section(section) for key, value in values.items(): config.set(section, key, value) for path in paths: if path: config.read(path) return 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"))
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"))
def setUp(self): try: from configparser import RawConfigParser except ImportError: from ConfigParser import RawConfigParser config = RawConfigParser() config.add_section('ScriptFilter') config.set('ScriptFilter', 'scriptdir', os.path.abspath( os.path.dirname(__file__) + '/testdata/scriptfilter')) self.candidate = ScriptFilter(config)
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 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 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 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 setUp(self): self.testfile = "/tmp/fuglu_override_test.db" if os.path.exists(self.testfile): os.remove(self.testfile) # important: 4 slashes for absolute paths! self.testdb = "sqlite:///%s" % self.testfile config = RawConfigParser() config.add_section('databaseconfig') config.set('databaseconfig', 'dbconnectstring', self.testdb) config.set('databaseconfig', "sql", "SELECT value FROM fugluconfig WHERE section=:section AND option=:option AND scope IN ('$GLOBAL','%'||:to_domain,:to_address) ORDER BY SCOPE DESC") self.config = config self.create_database()
def load(paths=(), extra_config=None): config = ConfigParser() for section, values in INITIAL_CONFIG.items(): config.add_section(section) for key, data in values.items(): config.set(section, key, data["value"]) if extra_config: for section, values in extra_config.items(): for key, value in values.items(): config.set(section, key, value) for path in paths: if path: config.read(path) return config
def create_section_file(dico): ''' Convert a dictionary of dictionary in section file. ''' parser = RawConfigParser() for section, options in dico.items(): parser.add_section(section) for option, value in options.items(): parser.set(section, option, value) fp = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'selenose.cfg') fd = open(fp, 'w') parser.write(fd) fd.close() return fp
def setUp(self): try: from configparser import RawConfigParser except ImportError: from ConfigParser import RawConfigParser config = RawConfigParser() config.add_section('FprotPlugin') config.set('FprotPlugin', 'host', 'localhost') config.set('FprotPlugin', 'port', '10200') config.set('FprotPlugin', 'timeout', '20') config.set('FprotPlugin', 'maxsize', '10485000') config.set('FprotPlugin', 'retries', '3') config.set('FprotPlugin', 'networkmode', '0') self.candidate = FprotPlugin(config)
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 _generate_sample_configuration(): sample_config = RawConfigParser() sample_config.add_section("BOT") sample_config.set("BOT", "BOT", "nltk.chat.zen.zen_chatbot") sample_config.set("BOT", "SLEEP", 120) sample_config.add_section("EMAIL") sample_config.set("EMAIL", "USERNAME", None) sample_config.set("EMAIL", "PASSWORD", None) sample_config.set("EMAIL", "IMAP_SERVER", None) sample_config.set("EMAIL", "SMTP_SERVER", None) sample_config.set("EMAIL", "SMTP_PORT", 587) return sample_config