Python configparser.ConfigParser() Examples
The following are 30
code examples of configparser.ConfigParser().
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 also want to check out all available functions/classes of the module
configparser
, or try the search function
.
Example #1
Source File: ProxHTTPSProxy.py From ProxHTTPSProxyMII with 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 #2
Source File: plugin_loader.py From vt-ida-plugin with 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
Source File: base.py From grimoirelab-sortinghat with 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 #4
Source File: setup.py From PyOptiX with 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
Source File: configparserwrapper.py From CAMISIM with 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 #6
Source File: test_cmd_init.py From grimoirelab-sortinghat with 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
Source File: bot_service_helper.py From JJMumbleBot with 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
Source File: qq_spider.py From QQ_zone with 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
Source File: server.py From syzygy-tables.info with 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
Source File: __init__.py From MarkdownPicPicker with 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
Source File: autostart.py From daily-wallpaper with 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
Source File: macros_widget.py From kivy-smoothie-host with 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
Source File: firefox_decrypt.py From firefox_decrypt with 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
Source File: nlg_sc_lstm.py From ConvLab with 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 #15
Source File: nlu.py From ConvLab with 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 #16
Source File: config.py From GSIL with 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 #17
Source File: config.py From GSIL with 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 #18
Source File: system.py From raveberry with 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 #19
Source File: _config.py From tekore with 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 #20
Source File: config.py From raspiblitz with 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 #21
Source File: blitz.configcheck.py From raspiblitz with 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
Source File: parsetime.py From Jtyoui with 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 #23
Source File: splunk_platform.py From misp42splunk with 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 #24
Source File: ta_data_loader.py From misp42splunk with 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 #25
Source File: splunk_platform.py From misp42splunk with 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 #26
Source File: run_woz.py From ConvLab with 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 #27
Source File: blitz.configcheck.py From raspiblitz with MIT License | 5 votes |
def get_str_clean(cp_section, key, default_value): """take a ConfigParser section, get key and strip leading and trailing \' and \" chars""" value = cp_section.get(key, default_value) if not value: return "" return value.lstrip('"').lstrip("'").rstrip('"').rstrip("'")
Example #28
Source File: config.py From raspiblitz with MIT License | 5 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.auto_nat_discovery = default_s.getboolean("autoNatDiscovery", self.auto_nat_discovery) self.auto_pilot = default_s.getboolean("autoPilot", self.auto_pilot) self.auto_unlock = default_s.getboolean("autoUnlock", self.auto_unlock) self.chain = get_str_clean(default_s, "chain", self.chain) self.dynDomain = get_str_clean(default_s, "dynDomain", self.dynDomain) self.dyn_update_url = get_str_clean(default_s, "dynUpdateUrl", self.dyn_update_url) self.hostname = get_str_clean(default_s, "hostname", self.hostname) self.invoice_allow_donations = default_s.getboolean("invoiceAllowDonations", self.invoice_allow_donations) self.invoice_default_amount = get_int_safe(default_s, "invoiceDefaultAmount", self.invoice_default_amount) self.lcd_rotate = default_s.getboolean("lcdrotate", self.lcd_rotate) self.lnd_address = get_str_clean(default_s, "lndAddress", self.lnd_address) self.lnd_port = get_str_clean(default_s, "lndPort", self.lnd_port) self.network = get_str_clean(default_s, "network", self.network) self.public_ip = get_str_clean(default_s, "publicIP", self.public_ip) self.rtl_web_interface = default_s.getboolean("rtlWebinterface", self.rtl_web_interface) self.run_behind_tor = default_s.getboolean("runBehindTor", self.run_behind_tor) self.ssh_tunnel = get_str_clean(default_s, "sshtunnel", self.ssh_tunnel) self.touchscreen = default_s.getboolean("touchscreen", self.touchscreen) self.version = get_str_clean(default_s, "raspiBlitzVersion", self.version)
Example #29
Source File: create_metadata.py From CAMISIM with Apache License 2.0 | 5 votes |
def read_config(path): """ Reads the config file used for the creation of the data set """ config_path = os.path.join(path, "config.ini") config = ConfigParser() config.read(config_path) return config
Example #30
Source File: blitz.configcheck.py From raspiblitz with MIT License | 5 votes |
def get_int_safe(cp_section, key, default_value): """take a ConfigParser section, get key that might be string encoded int and return int""" try: value = cp_section.getint(key, default_value) except ValueError: _value = cp_section.get(key) value = int(_value.strip("'").strip('"')) # this will raise an Exception if int() fails! return value