當前位置: 首頁>>代碼示例>>Python>>正文


Python configparser.ConfigParser方法代碼示例

本文整理匯總了Python中configparser.ConfigParser方法的典型用法代碼示例。如果您正苦於以下問題:Python configparser.ConfigParser方法的具體用法?Python configparser.ConfigParser怎麽用?Python configparser.ConfigParser使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在configparser的用法示例。


在下文中一共展示了configparser.ConfigParser方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: write_config

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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 
開發者ID:VirusTotal,項目名稱:vt-ida-plugin,代碼行數:18,代碼來源:plugin_loader.py

示例2: __init__

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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 
開發者ID:CAMI-challenge,項目名稱:CAMISIM,代碼行數:20,代碼來源:configparserwrapper.py

示例3: copy_dependencies

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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 
開發者ID:YangCatalog,項目名稱:bottle-yang-extractor-validator,代碼行數:19,代碼來源:views.py

示例4: save_pyoptix_conf

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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.") 
開發者ID:ozen,項目名稱:PyOptiX,代碼行數:25,代碼來源:setup.py

示例5: setUpClass

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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() 
開發者ID:chaoss,項目名稱:grimoirelab-sortinghat,代碼行數:18,代碼來源:base.py

示例6: setUp

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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) 
開發者ID:chaoss,項目名稱:grimoirelab-sortinghat,代碼行數:20,代碼來源:test_cmd_init.py

示例7: initialize_settings

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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. 
開發者ID:DuckBoss,項目名稱:JJMumbleBot,代碼行數:19,代碼來源:bot_service_helper.py

示例8: __init__

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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={} 
開發者ID:nanxung,項目名稱:QQ_zone,代碼行數:19,代碼來源:qq_spider.py

示例9: main

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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) 
開發者ID:niklasf,項目名稱:syzygy-tables.info,代碼行數:19,代碼來源:server.py

示例10: read_config

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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 
開發者ID:kingname,項目名稱:MarkdownPicPicker,代碼行數:25,代碼來源:__init__.py

示例11: create

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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) 
開發者ID:atareao,項目名稱:daily-wallpaper,代碼行數:26,代碼來源:autostart.py

示例12: _new_macro

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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)) 
開發者ID:wolfmanjm,項目名稱:kivy-smoothie-host,代碼行數:23,代碼來源:macros_widget.py

示例13: read_profiles

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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 
開發者ID:unode,項目名稱:firefox_decrypt,代碼行數:27,代碼來源:firefox_decrypt.py

示例14: parse

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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 
開發者ID:ConvLab,項目名稱:ConvLab,代碼行數:24,代碼來源:run_woz.py

示例15: parse

# 需要導入模塊: import configparser [as 別名]
# 或者: from configparser import ConfigParser [as 別名]
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 
開發者ID:ConvLab,項目名稱:ConvLab,代碼行數:24,代碼來源:nlg_sc_lstm.py


注:本文中的configparser.ConfigParser方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。