Python configparser.ConfigParser() Examples
The following are 30 code examples for showing how to use configparser.ConfigParser(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
configparser
, or try the search function
.
Example 1
Project: bottle-yang-extractor-validator Author: YangCatalog File: views.py License: BSD 2-Clause "Simplified" License | 7 votes |
def copy_dependencies(f): config_path = '/etc/yangcatalog/yangcatalog.conf' config = ConfigParser.ConfigParser() config._interpolation = ConfigParser.ExtendedInterpolation() config.read(config_path) yang_models = config.get('Directory-Section', 'save-file-dir') tmp = config.get('Directory-Section', 'temp') out = f.getvalue() letters = string.ascii_letters suffix = ''.join(random.choice(letters) for i in range(8)) dep_dir = '{}/yangvalidator-dependencies-{}'.format(tmp, suffix) os.mkdir(dep_dir) dependencies = out.split(':')[1].strip().split(' ') for dep in dependencies: for file in glob.glob(r'{}/{}*.yang'.format(yang_models, dep)): shutil.copy(file, dep_dir) return dep_dir
Example 2
Project: vt-ida-plugin Author: VirusTotal File: plugin_loader.py License: Apache License 2.0 | 6 votes |
def write_config(self): """Write user's configuration file.""" logging.debug('[VT Plugin] Writing user config file: %s', self.vt_cfgfile) try: parser = configparser.ConfigParser() config_file = open(self.vt_cfgfile, 'w') parser.add_section('General') parser.set('General', 'auto_upload', str(self.auto_upload)) parser.write(config_file) config_file.close() except: logging.error('[VT Plugin] Error while creating the user config file.') return False return True
Example 3
Project: CAMISIM Author: CAMI-challenge File: configparserwrapper.py License: Apache License 2.0 | 6 votes |
def __init__(self, logfile=None, verbose=True): """ Wrapper for the SafeConfigParser class for easy use. @attention: config_file argument may be file path or stream. @param logfile: file handler or file path to a log file @type logfile: file | FileIO | StringIO | None @param verbose: No stdout or stderr messages. Warnings and errors will be only logged to a file, if one is given @type verbose: bool @return: None @rtype: None """ super(ConfigParserWrapper, self).__init__( label="ConfigParserWrapper", logfile=logfile, verbose=verbose) self._config = ConfigParser() self._config_file_path = None
Example 4
Project: PyOptiX Author: ozen File: setup.py License: MIT License | 6 votes |
def save_pyoptix_conf(nvcc_path, compile_args, include_dirs, library_dirs, libraries): try: config = ConfigParser() config.add_section('pyoptix') config.set('pyoptix', 'nvcc_path', nvcc_path) config.set('pyoptix', 'compile_args', os.pathsep.join(compile_args)) config.set('pyoptix', 'include_dirs', os.pathsep.join(include_dirs)) config.set('pyoptix', 'library_dirs', os.pathsep.join(library_dirs)) config.set('pyoptix', 'libraries', os.pathsep.join(libraries)) tmp = NamedTemporaryFile(mode='w+', delete=False) config.write(tmp) tmp.close() config_path = os.path.join(os.path.dirname(sys.executable), 'pyoptix.conf') check_call_sudo_if_fails(['cp', tmp.name, config_path]) check_call_sudo_if_fails(['cp', tmp.name, '/etc/pyoptix.conf']) check_call_sudo_if_fails(['chmod', '644', config_path]) check_call_sudo_if_fails(['chmod', '644', '/etc/pyoptix.conf']) except Exception as e: print("PyOptiX configuration could not be saved. When you use pyoptix.Compiler, " "nvcc path must be in PATH, OptiX library paths must be in LD_LIBRARY_PATH, and pyoptix.Compiler " "attributes should be set manually.")
Example 5
Project: grimoirelab-sortinghat Author: chaoss File: base.py License: GNU General Public License v3.0 | 6 votes |
def setUpClass(cls): config = configparser.ConfigParser() config.read(CONFIG_FILE) cls.db_kwargs = {'user': config['Database']['user'], 'password': config['Database']['password'], 'database': config['Database']['name'], 'host': config['Database']['host'], 'port': config['Database']['port']} if 'create' in config['Database']: cls.create = config['Database'].getboolean('create') else: cls.create = False if cls.create: Database.create(**cls.db_kwargs) cls.db = Database(**cls.db_kwargs) cls.db.clear()
Example 6
Project: grimoirelab-sortinghat Author: chaoss File: test_cmd_init.py License: GNU General Public License v3.0 | 6 votes |
def setUp(self): if not hasattr(sys.stdout, 'getvalue') and not hasattr(sys.stderr, 'getvalue'): self.fail('This test needs to be run in buffered mode') # Create temporal names for the registry self.name = 'tmp' + uuid.uuid4().hex self.name_reuse = 'tmp' + uuid.uuid4().hex config = configparser.ConfigParser() config.read(CONFIG_FILE) # Create command self.kwargs = {'user': config['Database']['user'], 'password': config['Database']['password'], 'host': config['Database']['host'], 'port': config['Database']['port']} self.cmd = Init(database=self.name, **self.kwargs) self.cmd_reuse = Init(database=self.name_reuse, **self.kwargs)
Example 7
Project: JJMumbleBot Author: DuckBoss File: bot_service_helper.py License: GNU General Public License v3.0 | 6 votes |
def initialize_settings(): import configparser global_settings.cfg = configparser.ConfigParser() global_settings.cfg.read(f"{dir_utils.get_main_dir()}/cfg/config.ini") runtime_settings.tick_rate = float(global_settings.cfg[C_MAIN_SETTINGS][P_CMD_TICK_RATE]) runtime_settings.cmd_hist_lim = int(global_settings.cfg[C_MAIN_SETTINGS][P_CMD_MULTI_LIM]) runtime_settings.cmd_token = global_settings.cfg[C_MAIN_SETTINGS][P_CMD_TOKEN] runtime_settings.use_logging = global_settings.cfg.getboolean(C_LOGGING, P_LOG_ENABLE, fallback=False) runtime_settings.max_logs = global_settings.cfg[C_LOGGING][P_LOG_MAX] runtime_settings.cmd_queue_lim = int(global_settings.cfg[C_MAIN_SETTINGS][P_CMD_QUEUE_LIM]) runtime_settings.cmd_hist_lim = int(global_settings.cfg[C_MAIN_SETTINGS][P_CMD_HIST_LIM]) if len(runtime_settings.cmd_token) != 1: rprint("ERROR: The command token must be a single character! Reverting to the default: '!' token.") runtime_settings.cmd_token = '!' # Initializes only safe-mode applicable plugins.
Example 8
Project: QQ_zone Author: nanxung File: qq_spider.py License: Apache License 2.0 | 6 votes |
def __init__(self): self.web=webdriver.Chrome() self.web.get('https://user.qzone.qq.com') config = configparser.ConfigParser(allow_no_value=False) config.read('userinfo.ini') self.__username =config.get('qq_info','qq_number') self.__password=config.get('qq_info','qq_password') self.headers={ 'host': 'h5.qzone.qq.com', 'accept-encoding':'gzip, deflate, br', 'accept-language':'zh-CN,zh;q=0.8', 'accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'user-agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36', 'connection': 'keep-alive' } self.req=requests.Session() self.cookies={}
Example 9
Project: syzygy-tables.info Author: niklasf File: server.py License: GNU Affero General Public License v3.0 | 6 votes |
def main(argv): logging.basicConfig(level=logging.DEBUG) config = configparser.ConfigParser() config.read([ os.path.join(os.path.dirname(__file__), "config.default.ini"), os.path.join(os.path.dirname(__file__), "config.ini"), ] + argv) bind = config.get("server", "bind") port = config.getint("server", "port") app = make_app(config) print("* Server name: ", config.get("server", "name")) print("* Base url: ", config.get("server", "base_url")) aiohttp.web.run_app(app, host=bind, port=port, access_log=None)
Example 10
Project: MarkdownPicPicker Author: kingname File: __init__.py License: GNU General Public License v3.0 | 6 votes |
def read_config(): _dict = {} if getattr(sys, 'frozen', None): config_path = os.path.join(os.path.dirname(sys.executable), 'config', 'config.ini') else: config_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'config.ini') if not os.path.exists(config_path): print('can not find the config.ini, use the default sm uploader.' 'attention: this website may breakdown in the future, only used temporarily.') _dict['picture_host'] = 'SmUploader' return _dict configs = ConfigParser() configs.read(config_path) _dict['picture_folder'] = configs['basic'].get('picture_folder', '') _dict['picture_suffix'] = configs['basic'].get('picture_suffix', '') _dict['picture_host'] = configs['basic'].get('picture_host', '') _dict['config_path'] = config_path if _dict['picture_host']: _dict['uploader_info'] = configs[_dict['picture_host']] return _dict
Example 11
Project: daily-wallpaper Author: atareao File: autostart.py License: MIT License | 6 votes |
def create(self, autostart=None): if autostart is None: autostart = self.autostart execfile = '/usr/share/national-geographic-wallpaper/ngdownloader.py' config = configparser.ConfigParser() config['Desktop Entry'] = { 'Type': 'Application', 'Version': '1.0', 'Name': 'National Geographic Wallpaper', 'Exec': '/usr/bin/python3 {0}'.format(execfile), 'Hidden': 'false', 'NoDisplay': 'false', 'Terminal': 'false', 'StartupNotify': 'false', 'X-GNOME-Autostart-enabled': str(autostart).lower(), 'X-GNOME-Autostart-Delay': 5, 'X-GNOME-Autostart-Phase': 'Applications', 'X-MATE-Autostart-enabled': str(autostart).lower(), 'X-MATE-Autostart-Delay': 5, 'X-MATE-Autostart-Phase': 'Applications', 'NGV': '1.0' } with open(self.autostart_file, 'w') as configfile: config.write(configfile)
Example 12
Project: kivy-smoothie-host Author: wolfmanjm File: macros_widget.py License: GNU General Public License v3.0 | 6 votes |
def _new_macro(self, opts): if opts and opts['Name'] and opts['Command']: btn = Factory.MacroButton() btn.text = opts['Name'] btn.bind(on_press=partial(self.send, opts['Command'])) btn.ud = True self.add_widget(btn) # write it to macros.ini try: config = configparser.ConfigParser() config.read(self.macro_file) if not config.has_section("macro buttons"): config.add_section("macro buttons") config.set("macro buttons", opts['Name'], opts['Command']) with open(self.macro_file, 'w') as configfile: config.write(configfile) Logger.info('MacrosWidget: added macro button {}'.format(opts['Name'])) except Exception as err: Logger.error('MacrosWidget: ERROR - exception writing config file: {}'.format(err))
Example 13
Project: firefox_decrypt Author: unode File: firefox_decrypt.py License: GNU General Public License v3.0 | 6 votes |
def read_profiles(basepath, list_profiles): """ Parse Firefox profiles in provided location. If list_profiles is true, will exit after listing available profiles. """ profileini = os.path.join(basepath, "profiles.ini") LOG.debug("Reading profiles from %s", profileini) if not os.path.isfile(profileini): LOG.warning("profile.ini not found in %s", basepath) raise Exit(Exit.MISSING_PROFILEINI) # Read profiles from Firefox profile folder profiles = ConfigParser() profiles.read(profileini) LOG.debug("Read profiles %s", profiles.sections()) if list_profiles: LOG.debug("Listing available profiles...") print_sections(get_sections(profiles), sys.stdout) raise Exit(0) return profiles
Example 14
Project: ConvLab Author: ConvLab File: run_woz.py License: MIT License | 6 votes |
def parse(): parser = argparse.ArgumentParser(description='Train dialogue generator') parser.add_argument('--mode', type=str, default='interact', help='train or test') parser.add_argument('--model_path', type=str, default='sclstm.pt', help='saved model path') parser.add_argument('--n_layer', type=int, default=1, help='# of layers in LSTM') parser.add_argument('--percent', type=float, default=1, help='percentage of training data') parser.add_argument('--beam_search', type=str2bool, default=False, help='beam_search') parser.add_argument('--attn', type=str2bool, default=True, help='whether to use attention or not') parser.add_argument('--beam_size', type=int, default=10, help='number of generated sentences') parser.add_argument('--bs', type=int, default=256, help='batch size') parser.add_argument('--lr', type=float, default=0.0025, help='learning rate') parser.add_argument('--user', type=str2bool, default=False, help='use user data') args = parser.parse_args() config = configparser.ConfigParser() if args.user: config.read('config/config_usr.cfg') else: config.read('config/config.cfg') config.set('DATA','dir', os.path.dirname(os.path.abspath(__file__))) return args, config
Example 15
Project: ConvLab Author: ConvLab File: nlg_sc_lstm.py License: MIT License | 6 votes |
def parse(is_user): if is_user: args = { 'model_path': 'sclstm_usr.pt', 'n_layer': 1, 'beam_size': 10 } else: args = { 'model_path': 'sclstm.pt', 'n_layer': 1, 'beam_size': 10 } config = configparser.ConfigParser() if is_user: config.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config/config_usr.cfg')) else: config.read(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config/config.cfg')) config.set('DATA', 'dir', os.path.dirname(os.path.abspath(__file__))) return args, config
Example 16
Project: ConvLab Author: ConvLab File: nlu.py License: MIT License | 6 votes |
def __init__(self, config_file=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config/multiwoz.cfg'), model_file=None): self.config = configparser.ConfigParser() self.config.read(config_file) self.c = Classifier.classifier(self.config) model_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), self.config.get("train", "output")) model_dir = os.path.dirname(model_path) if not os.path.exists(model_path): if not os.path.exists(model_dir): os.makedirs(model_dir) if not model_file: print('Load from ', os.path.join(model_dir, 'svm_multiwoz.zip')) archive = zipfile.ZipFile(os.path.join(model_dir, 'svm_multiwoz.zip'), 'r') else: print('Load from model_file param') archive_file = cached_path(model_file) archive = zipfile.ZipFile(archive_file, 'r') archive.extractall(os.path.dirname(model_dir)) archive.close() self.c.load(model_path)
Example 17
Project: misp42splunk Author: remg427 File: splunk_platform.py License: GNU Lesser General Public License v3.0 | 6 votes |
def _get_conf_stanzas(conf_name): """ :return: {stanza_name: stanza_configs}, dict of dict """ res = _get_merged_conf_raw(conf_name) res = res.decode('utf-8') res = StringIO(res) parser = ConfigParser() parser.optionxform = str if PY_VERSION >= (3, 2): parser.read_file(res) else: parser.readfp(res) res = {} for section in parser.sections(): res[section] = {item[0]: item[1] for item in parser.items(section)} return res
Example 18
Project: misp42splunk Author: remg427 File: ta_data_loader.py License: GNU Lesser General Public License v3.0 | 6 votes |
def _read_default_settings(): cur_dir = op.dirname(op.abspath(__file__)) setting_file = op.join(cur_dir,"../../","splunktalib", "setting.conf") parser = configparser.ConfigParser() parser.read(setting_file) settings = {} keys = ("process_size", "thread_min_size", "thread_max_size", "task_queue_size") for option in keys: try: settings[option] = parser.get("global", option) except configparser.NoOptionError: settings[option] = -1 try: settings[option] = int(settings[option]) except ValueError: settings[option] = -1 log.logger.debug("settings: %s", settings) return settings
Example 19
Project: misp42splunk Author: remg427 File: splunk_platform.py License: GNU Lesser General Public License v3.0 | 6 votes |
def _get_conf_stanzas(conf_name): """ :return: {stanza_name: stanza_configs}, dict of dict """ res = _get_merged_conf_raw(conf_name) res = res.decode('utf-8') res = StringIO(res) parser = ConfigParser() parser.optionxform = str if PY_VERSION >= (3, 2): parser.read_file(res) else: parser.readfp(res) res = {} for section in parser.sections(): res[section] = {item[0]: item[1] for item in parser.items(section)} return res
Example 20
Project: Jtyoui Author: jtyoui File: parsetime.py License: MIT License | 6 votes |
def load_config(self, map_path=None, re_path=None): """自定义日期解析映射表和匹配日期的正则表 :param map_path: 解析日期的映射表 :param re_path: 匹配日期的正则表 """ path = os.path.dirname(__file__) self.map = configparser.ConfigParser() if map_path: self.map.read(map_path, encoding='UTF-8') else: self.map.read(path + os.sep + 'map.ini', encoding='UTF-8') if re_path: self.re = reader_conf(re_path) else: self.re = reader_conf(path + os.sep + 're.cfg')
Example 21
Project: raspiblitz Author: rootzoll File: blitz.configcheck.py License: MIT License | 6 votes |
def reload(self): """load config from file""" parser = ConfigParser() log.debug("loading config from file: {}".format(self.abs_path)) with open(self.abs_path) as f: parser.read_string("[{}]\n".format(DEFAULTSECT) + f.read()) default_s = parser[DEFAULTSECT] self.base_image = get_str_clean(default_s, "baseimage", self.base_image) self.chain = get_str_clean(default_s, "chain", self.chain) self.message = get_str_clean(default_s, "message", self.message) self.network = get_str_clean(default_s, "network", self.network) self.setup_step = get_int_safe(default_s, "setupStep", self.setup_step) self.state = get_str_clean(default_s, "state", self.state) self.undervoltage_reports = get_int_safe(default_s, "undervoltageReports", self.undervoltage_reports)
Example 22
Project: raspiblitz Author: rootzoll File: config.py License: MIT License | 6 votes |
def reload(self): """load config from file""" parser = ConfigParser() log.debug("loading RaspiBlitzInfo config from file: {}".format(self.abs_path)) with open(self.abs_path) as f: parser.read_string("[{}]\n".format(DEFAULTSECT) + f.read()) default_s = parser[DEFAULTSECT] self.base_image = get_str_clean(default_s, "baseimage", self.base_image) self.chain = get_str_clean(default_s, "chain", self.chain) self.message = get_str_clean(default_s, "message", self.message) self.network = get_str_clean(default_s, "network", self.network) self.setup_step = get_int_safe(default_s, "setupStep", self.setup_step) self.state = get_str_clean(default_s, "state", self.state) self.undervoltage_reports = get_int_safe(default_s, "undervoltageReports", self.undervoltage_reports)
Example 23
Project: tekore Author: felix-hilden File: _config.py License: MIT License | 6 votes |
def _read_configfile(file_path: str, force: bool = True) -> ConfigParser: """ Read configuration from INI file. Parameters ---------- file_path path of the configuration file force force reading of the file, fail if not found """ c = ConfigParser() c.optionxform = str if force: with open(file_path, 'r') as f: c.read_file(f) else: c.read(file_path) return c
Example 24
Project: raveberry Author: raveberry File: system.py License: GNU Lesser General Public License v3.0 | 6 votes |
def _check_mopidy_extensions_user(self) -> Dict[str, Tuple[bool, str]]: config = subprocess.run( ["mopidy", "config"], stdout=subprocess.PIPE, universal_newlines=True, check=True, ).stdout parser = configparser.ConfigParser() parser.read_string(config) extensions = {} for extension in ["spotify", "enabled"]: try: if parser[extension]["enabled"] == "true": extensions[extension] = ( True, "Extension probably functional", ) except KeyError: extensions[extension] = (False, "Extension disabled") return extensions
Example 25
Project: GSIL Author: FeeiCN File: config.py License: GNU General Public License v3.0 | 6 votes |
def get(level1=None, level2=None): """ Get config value :param level1: :param level2: :return: string """ if level1 is None and level2 is None: return config = configparser.ConfigParser() config.read(config_path) value = None try: value = config.get(level1, level2) except Exception as e: print(level1, level2) traceback.print_exc() print("GSIL/config.gsil file configure failed.\nError: {0}".format(e)) return value # GitHub tokens
Example 26
Project: GSIL Author: FeeiCN File: config.py License: GNU General Public License v3.0 | 6 votes |
def get(self, extend_config_file): config = configparser.ConfigParser() config.read(self.base_config_file) base_dict = config._sections config = configparser.ConfigParser() config.read(extend_config_file) target_dict = config._sections for b_key, b_value in base_dict.items(): for t_key, t_value in target_dict.items(): if b_key == t_key: b_ports = b_value['ports'].split(',') t_ports = t_value['ports'].split(',') for t_port in t_ports: if t_port not in b_ports: b_ports.append(t_port) base_dict[b_key]['ports'] = ','.join(b_ports) return base_dict
Example 27
Project: ProxHTTPSProxyMII Author: wheever File: ProxHTTPSProxy.py License: MIT License | 6 votes |
def loadConfig(self): # self.conf has to be inited each time for reloading self.conf = configparser.ConfigParser(allow_no_value=True, delimiters=('=',), inline_comment_prefixes=('#',)) self.conf.read(self.file) self.pools = [] proxy_sections = [section for section in self.conf.sections() if section.startswith('PROXY')] for section in proxy_sections: proxy = section.split()[1] self.pools.append(dict(proxy=proxy, pool=self.setProxyPool(proxy), patterns=list(self.conf[section].keys()))) default_proxy = self.conf['GENERAL'].get('DefaultProxy') default_pool = (self.setProxyPool(default_proxy) if default_proxy else [urllib3.PoolManager(num_pools=10, maxsize=8, timeout=self.timeout, **self.sslparams), urllib3.PoolManager(num_pools=10, maxsize=8, timeout=self.timeout)]) self.pools.append({'proxy': default_proxy, 'pool': default_pool, 'patterns': '*'}) self.noverifylist = list(self.conf['SSL No-Verify'].keys()) self.blacklist = list(self.conf['BLACKLIST'].keys()) self.sslpasslist = list(self.conf['SSL Pass-Thru'].keys()) self.bypasslist = list(self.conf['BYPASS URL'].keys())
Example 28
Project: mutatest Author: EvanKepner File: cli.py License: MIT License | 5 votes |
def read_ini_config( config_path: Path, sections: Optional[List[str]] = None ) -> configparser.SectionProxy: """Read a config_path using ConfigParser Args: config_path: path to the INI config file sections: sections of config file to return, default to ['mutatest'] if None Returns: config section proxy Raises: KeyError if ``section`` not in ``config_path``. """ sections = sections or ["mutatest"] config = configparser.ConfigParser() # ensures [ mutatest ] is valid like [mutatest] in a section key config.SECTCRE = re.compile(r"\[ *(?P<header>[^]]+?) *\]") # type: ignore config.read(config_path) # Attempt sections in the list, if none are matched raise a KeyError for section in sections: try: return config[section] except KeyError: continue raise KeyError
Example 29
Project: mlbv Author: kmac File: config.py License: GNU General Public License v3.0 | 5 votes |
def __init_configparser(self, script_name): # now look for config file parser = configparser.ConfigParser() parser.read_dict(self.defaults) ini_file = os.path.join(self.dir, 'config') if os.path.exists(ini_file): LOG.debug("Reading config file: %s", ini_file) with open(ini_file, 'r') as openf: config_string = '[{}]\n'.format(script_name) + openf.read() parser.read_string(config_string) return parser[script_name]
Example 30
Project: python-clean-architecture Author: pcah File: ini.py License: MIT License | 5 votes |
def load_ini_from_filepath(filepath: t.Union[str, 'pathlib.Path']) -> dict: config = ConfigParser() config.read(filepath) return {name: dict(section) for name, section in config.items()}