当前位置: 首页>>代码示例>>Python>>正文


Python ConfigParser.get方法代码示例

本文整理汇总了Python中ConfigParser.ConfigParser.get方法的典型用法代码示例。如果您正苦于以下问题:Python ConfigParser.get方法的具体用法?Python ConfigParser.get怎么用?Python ConfigParser.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在ConfigParser.ConfigParser的用法示例。


在下文中一共展示了ConfigParser.get方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
def main():
    options, args = parser.parse_args()
    
    if len(args) == 1 and args[0].endswith('.odt'):
        args.append(args[0][:-4])
    if len(args) == 2:
        filename, targetdir = args
        convert_odt(filename, targetdir, debug=options.debug,
            options={
                'download_source_link': options.download_source_link
                })
    elif len(args) == 1:
        configname = os.path.abspath(args[0])
        configdir = os.path.dirname(configname)
        config = ConfigParser()
        config.read(configname)
        for section in config.sections():
            filename = config.has_option(section, 'filename') and \
                config.get(section, 'filename') or section
            filename = os.path.normpath(
                os.path.join(configdir, filename))
            targetdir = config.has_option(section, 'targetdir') and \
                config.get(section, 'targetdir') or '.'
            targetdir = os.path.normpath(
                os.path.join(configdir, targetdir))
            print "Converting %s in %s" % (filename, targetdir)
            convert_odt(filename, targetdir, debug=options.debug,
                options={'download_source_link': options.download_source_link})
开发者ID:dysseus88,项目名称:virtuelium,代码行数:30,代码来源:odt2sphinx.py

示例2: _load_object_post_as_copy_conf

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
    def _load_object_post_as_copy_conf(self, conf):
        if ('object_post_as_copy' in conf or '__file__' not in conf):
            # Option is explicitly set in middleware conf. In that case,
            # we assume operator knows what he's doing.
            # This takes preference over the one set in proxy app
            return

        cp = ConfigParser()
        if os.path.isdir(conf['__file__']):
            read_conf_dir(cp, conf['__file__'])
        else:
            cp.read(conf['__file__'])

        try:
            pipe = cp.get("pipeline:main", "pipeline")
        except (NoSectionError, NoOptionError):
            return

        proxy_name = pipe.rsplit(None, 1)[-1]
        proxy_section = "app:" + proxy_name

        try:
            conf['object_post_as_copy'] = cp.get(proxy_section,
                                                 'object_post_as_copy')
        except (NoSectionError, NoOptionError):
            pass
开发者ID:ISCAS-VDI,项目名称:swift-base,代码行数:28,代码来源:copy.py

示例3: getMysqlConfig

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
	def getMysqlConfig(self, db = 'test'):
		"""获取mysql连接配置

		- 依赖配置文件[conf/config.ini],节点[db]

		Returns:
			dbconfig dict.
		"""

		try:
			cf = ConfigParser()
			cf.read('conf/config.ini')
			dbconfig = {
				'host': cf.get('db', 'host'), 
				'port': cf.getint('db', 'port'), 
				'user': cf.get('db', 'user'), 
				'passwd': cf.get('db', 'passwd'), 
				'db': db
			}
			return dbconfig			
		except Exception as e:
			error = """Can't load config from [conf/config.ini] or [db] node doesn't exist.\n
			Please make sure this file."""
			logging.warning(error)
			print(error)
			raise Exception(e)
开发者ID:haoyett,项目名称:somai_web,代码行数:28,代码来源:tool.py

示例4: _set_config_all

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
 def _set_config_all(self, path_to_file):
     out = sys.stdout
     if not os.access(path_to_file, os.R_OK):
         self.log.warning( "cannot access file %s" % path_to_file )
         return
     elif not self.env.config:
         self.log.warning( "cannot access config file trac.ini" )
         return
     
     cfg = ConfigParser()
     cfg.read(path_to_file)
     
     if os.access(self.env.path, os.W_OK):
         path_to_trac_ini = os.path.join(self.env.path, 'conf', 'trac.ini')
         shutil.copy(path_to_trac_ini, path_to_trac_ini + '.bak')
         out.write( "created a backup of trac.ini to %s.bak" % path_to_trac_ini )
         out.write('\n')
     else:
         out.write( "could not create backup of trac.ini - continue anyway? [y|n] "  )
         input = sys.stdin.readline()
         if not input or not input.strip() == 'y':
             return
     
     for sect in cfg.sections():
         for opt in cfg.options(sect):
             self.config.set(sect, opt, cfg.get(sect, opt))
             out.write( "added config [%s] %s = %s" % (sect, opt, cfg.get(sect, opt)) )
             out.write('\n')
     self.config.save()
开发者ID:nyuhuhuu,项目名称:trachacks,代码行数:31,代码来源:settings.py

示例5: get_value

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
    def get_value(self, section, option):
        """
        Retourne la valeur de l'option contenue dans la section passée en
        paramètre.
        """

        # On travaille sur le nom de la section parente
        # au cas où s'il s'agit d'une sous-section.
        parent_section = self.get_parent_section_name(section)


        # On vérifie d'abord que la section existe.
        if self.__spec_sections.has_key(parent_section):
            # Puis on récupère la spécification de la section.
            section_spec = self.__spec_sections.get(parent_section)
            option_type  = None

            # On parcours les options de la spécification à la recherche
            # du type de la valeur de l'option que l'on souhaite obtenir.
            for option_spec in section_spec[2]:
                if option_spec[0] == option:
                    option_type = option_spec[1]

            # Introuvable dans les options de la section ?
            # On regarde dans ceux de la sous-section si elle existe.
            if self.__spec_has_subsection(parent_section):
                for sub_option_spec in section_spec[3]:
                    if sub_option_spec[0] == option:
                        option_type = sub_option_spec[1]


            # On appelle la fonction qui va bien en fonction du type à obtenir.
            #
            # Les sous-sections héritent des options de leur section parente.
            # Si l'option n'existe pas dans la section, il doit sûrement s'agir
            # d'une sous-section. On cherche alors l'option dans la section
            # parente.
            if option_type == 'string':
                try:
                    return ConfigParser.get(self, section, option)
                except NoOptionError:
                    return ConfigParser.get(self, parent_section, option)

            if option_type == 'int':
                try:
                    return ConfigParser.getint(self, section, option)
                except NoOptionError:
                    return ConfigParser.getint(self, parent_section, option)

            if option_type == 'bool':
                try:
                    return ConfigParser.getboolean(self, section, option)
                except NoOptionError:
                    return ConfigParser.getboolean(self, parent_section, option)


            return None
        else:
            raise NameError("Invalid section name: '%(section)s'." % \
                            {'section': section})
开发者ID:spack,项目名称:nodetools,代码行数:62,代码来源:config.py

示例6: getVersionedFolderInfo

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
def getVersionedFolderInfo(dirPath):
	"""
	returns a list containing the following information about the asset in dirPath:
	[0] last person to check it out, if locked
	[1] last person to check it in
	[2] time it was last checked in
	[3] latest comment on checkin
	[4] if it is isInstalled
	[5] filepath to install directory
	"""
	if not isVersionedFolder(dirPath):
		raise Exception("Not a versioned folder")
	
	nodeInfo = []
	cp = ConfigParser()
	cp.read(os.path.join(dirPath, ".nodeInfo"))
	if cp.getboolean("Versioning", "locked"):
		nodeInfo.append(cp.get("Versioning", "lastcheckoutuser"))
	else:
		nodeInfo.append("")
	nodeInfo.append(cp.get("Versioning", "lastcheckinuser"))
	nodeInfo.append(cp.get("Versioning", "lastcheckintime"))
	versionNum = int(cp.get("Versioning", "latestversion"))
	latestVersion = "v"+("%03d" % versionNum) 
	if cp.has_section("Comments"):
		nodeInfo.append(cp.get("Comments", latestVersion))
	else:
		nodeInfo.append('')
	if isInstalled(dirPath):
		nodeInfo.append("Yes")
		nodeInfo.append(glob.glob(os.path.join(dirPath, 'stable', '*stable*'))[0])
	else:
		nodeInfo.append("No")
		nodeInfo.append("")
	return nodeInfo
开发者ID:byu-animation,项目名称:ramshorn-tools,代码行数:37,代码来源:utilities.py

示例7: main

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
def main(numthreads=10):
    t1 = time.time()
    queue = Queue()
    factory = TokenFactory()
    config = ConfigParser()
    config.read('vk_api.conf')

    url = API.get_url(
        app_id=config.get('api', 'id'), app_key=config.get('api', 'key'), 
        permissions=PERMISSIONS, redirect_uri=URI, display=DISPLAY, api_version=VERSION)

    # TODO: check token expiration
    token_pair = factory.get_token_pair()
    if not token_pair:
        token_pair = factory.store_token_pair(url)
    
    api = API(token=token_pair[0],user_id=token_pair[1])
    audio = api.audio
    data = audio.get

    if data:
        for item in data['response']['items']:
            queue.put(item)

        for i in range(numthreads):
            t = DownloadThread(queue, FILE_DIR)
            t.start()

        queue.join()


    t2 = time.time()
    print('Time: {0}'.format(t2-t1))
开发者ID:falkerson,项目名称:pyvk,代码行数:35,代码来源:vk_loader.py

示例8: get_ws_call

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
def get_ws_call(action, payload, uid):
    """
    This function builds the url for the outgoing call to the different errata ws.
    :param payload: payload to be posted
    :param action: one of the 4 actions: create, update, close, retrieve
    :param uid: in case of a retrieve call, uid is needed
    :return: requests call
    """
    config = ConfigParser()
    config.read(os.path.join(os.getenv('ISSUE_CLIENT_HOME'), 'esgf-client.ini'))
    if action not in ACTIONS:
        logging.error('Unrecognized command, refer to the docs for help or use -h, error code: {}.'.format(6))
        sys.exit(1)

    url = config.get(WEBSERVICE, URL_BASE)+config.get(WEBSERVICE, action)
    if action in [CREATE, UPDATE]:
        r = requests.post(url, json.dumps(payload), headers=HEADERS)
    elif action == CLOSE:
        r = requests.post(url+uid)
    elif action == RETRIEVE:
        r = requests.get(url+uid)
    else:
        r = requests.get(url)
    if r.status_code != requests.codes.ok:
        logging.error('Errata WS call has failed, please refer to the error text for further information: {0}'
                      ', error code: {1}'.format(r.text, 5))
        sys.exit(1)
    return r
开发者ID:Prodiguer,项目名称:esgf-issue-manager,代码行数:30,代码来源:utils.py

示例9: NightscoutConfig

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
class NightscoutConfig(object):
    FILENAME = 'config'
    SECTION = 'NightscoutMenubar'
    HOST = 'nightscout_host'
    USE_MMOL = 'use_mmol'

    def __init__(self, app_name):
        self.config_path = os.path.join(rumps.application_support(app_name), self.FILENAME)
        self.config = ConfigParser()
        self.config.read([self.config_path])
        if not self.config.has_section(self.SECTION):
            self.config.add_section(self.SECTION)
        if not self.config.has_option(self.SECTION, self.HOST):
            self.set_host('')
        if not self.config.has_option(self.SECTION, self.USE_MMOL):
            self.set_use_mmol(False)

    def get_host(self):
        return self.config.get(self.SECTION, self.HOST)

    def set_host(self, host):
        self.config.set(self.SECTION, self.HOST, host)
        with open(self.config_path, 'w') as f:
            self.config.write(f)

    def get_use_mmol(self):
        return bool(self.config.get(self.SECTION, self.USE_MMOL))

    def set_use_mmol(self, mmol):
        self.config.set(self.SECTION, self.USE_MMOL, 'true' if mmol else '')
        with open(self.config_path, 'w') as f:
            self.config.write(f)
开发者ID:mddub,项目名称:nightscout-osx-menubar,代码行数:34,代码来源:nightscout_osx_menubar.py

示例10: db_settings

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
def db_settings(backend=None):
    """
    Parses the contents of the db_settings.ini file and returns the connection
    settings of the required backend inside of a dictionary with the following
    keys:
      * backend
      * user
      * password
      * database
      * host (returned only by PostgreSQL backend)

    When backend is None the code looks for the value of the DATABASE environment
    variable. If the environment variable is not set Postgresql is going to be
    used as the default backend.
    """

    if not backend and os.getenv("DATABASE"):
        backend = os.getenv("DATABASE")
    elif not backend:
        backend = "postgresql"

    settings = {}

    config = ConfigParser()
    config.read(os.path.dirname(os.path.abspath(__file__)) + "/db_settings.ini")

    settings['backend']  = backend
    settings['user']     = config.get(backend, 'user')
    settings['password'] = config.get(backend, 'password')
    settings['database'] = config.get(backend, 'database')
    if backend == 'postgresql':
        settings['host'] = config.get(backend, 'host')

    return settings
开发者ID:Kilian-Petsch,项目名称:spacewalk,代码行数:36,代码来源:misc_functions.py

示例11: __init__

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
    def __init__(self, app, conf):
        self.app = app
        self.memcache_servers = conf.get("memcache_servers")
        serialization_format = conf.get("memcache_serialization_support")

        if not self.memcache_servers or serialization_format is None:
            path = os.path.join(conf.get("swift_dir", "/etc/swift"), "memcache.conf")
            memcache_conf = ConfigParser()
            if memcache_conf.read(path):
                if not self.memcache_servers:
                    try:
                        self.memcache_servers = memcache_conf.get("memcache", "memcache_servers")
                    except (NoSectionError, NoOptionError):
                        pass
                if serialization_format is None:
                    try:
                        serialization_format = memcache_conf.get("memcache", "memcache_serialization_support")
                    except (NoSectionError, NoOptionError):
                        pass

        if not self.memcache_servers:
            self.memcache_servers = "127.0.0.1:11211"
        if serialization_format is None:
            serialization_format = 2
        else:
            serialization_format = int(serialization_format)

        self.memcache = MemcacheRing(
            [s.strip() for s in self.memcache_servers.split(",") if s.strip()],
            allow_pickle=(serialization_format == 0),
            allow_unpickle=(serialization_format <= 1),
        )
开发者ID:sun7shines,项目名称:Cloudfs,代码行数:34,代码来源:memcache.py

示例12: Config

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
class Config(object):

    _raw_options = ("fetch_command", "player_command")
    _options = ("media_dir",)
    _expanduser = ("media_dir",)

    def __init__(self, my_file):
        my_file = os.path.expanduser(my_file)
        if not os.path.exists(my_file):
            with codecs.open(my_file, "w", encoding="utf-8") as fp:
                fp.write(config_file)
            raise MarrieError("Missing config file: %s. It will be created for you." % my_file)
        self._cp = ConfigParser()
        self._cp.read(my_file)
        for opt in self._raw_options + self._options:
            if not self._cp.has_option("config", opt):
                raise MarrieError("Missing needed config option: config:%s" % opt)

    def __getattr__(self, attr):
        opt = None
        if attr in self._raw_options:
            opt = self._cp.get("config", attr, True)
        elif attr in self._options:
            opt = self._cp.get("config", attr)
        elif attr == "podcast":
            opt = OrderedDict(self._cp.items("podcast"))
        if opt is None:
            raise AttributeError(attr)
        if attr in self._expanduser and not isinstance(opt, dict):
            return os.path.expanduser(opt)
        return opt
开发者ID:tlevine,项目名称:marrie,代码行数:33,代码来源:marrie.py

示例13: _populate_config_from_old_location

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
    def _populate_config_from_old_location(self, conf):
        if ('rate_limit_after_segment' in conf or
                'rate_limit_segments_per_sec' in conf or
                'max_get_time' in conf or
                '__file__' not in conf):
            return

        cp = ConfigParser()
        if os.path.isdir(conf['__file__']):
            read_conf_dir(cp, conf['__file__'])
        else:
            cp.read(conf['__file__'])

        try:
            pipe = cp.get("pipeline:main", "pipeline")
        except (NoSectionError, NoOptionError):
            return

        proxy_name = pipe.rsplit(None, 1)[-1]
        proxy_section = "app:" + proxy_name
        for setting in ('rate_limit_after_segment',
                        'rate_limit_segments_per_sec',
                        'max_get_time'):
            try:
                conf[setting] = cp.get(proxy_section, setting)
            except (NoSectionError, NoOptionError):
                pass
开发者ID:10389030,项目名称:swift,代码行数:29,代码来源:dlo.py

示例14: loadini

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
def loadini(struct, configfile):
    """Load ini and store in struct"""

    config_path = os.path.expanduser(configfile)

    config = ConfigParser()

    fill_config_with_default_values(config, {
        "general": {
            "host": "irc.quakenet.org",
            "port": 6667,
            "channels": "#scibbytest",
            "nickname": "scabby",
            "plugins_directory": "~/dev/src/scibby-plugins"
        }})

    config.read(config_path)

    struct.host = config.get("general", "host")
    struct.port = config.getint("general", "port")
    struct.channels = config.get("general", "channels").split(",")
    struct.nickname = config.get("general", "nickname")
    struct.plugins_directory = config.get("general", "plugins_directory")

    return struct
开发者ID:nosklo,项目名称:scibby,代码行数:27,代码来源:config.py

示例15: __init__

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import get [as 别名]
    def __init__(self, data_dir, configFile='glastopf.cfg'):
        if isinstance(configFile, ConfigParser):
            config = configFile
        else:
            config = ConfigParser()
            config.read(configFile)
        self.options = {'enabled': config.getboolean('taxii', 'enabled')}
        self.host = config.get('taxii', 'host')
        self.port = config.getint('taxii', 'port')
        self.inbox_path = config.get('taxii', 'inbox_path')
        self.use_https = config.getboolean('taxii', 'use_https')
        self.client = HttpClient()
        self.client.setProxy('noproxy')

        auth_credentials = {'username': config.get('taxii', 'auth_basic_username'),
                            'password': config.get('taxii', 'auth_basic_password'),
                            'key_file': config.get('taxii', 'auth_certificate_keyfile'),
                            'cert_file': config.get('taxii', 'auth_certificate_certfile')}
        self.client.setAuthCredentials(auth_credentials)

        if config.getboolean('taxii', 'use_auth_basic'):
            self.client.setAuthType(tc.HttpClient.AUTH_BASIC)
        elif config.getboolean('taxii', 'use_auth_certificate'):
            self.client.setAuthType(tc.HttpClient.AUTH_CERT)
        elif config.getboolean('taxii', 'use_auth_basic') and config.getboolean('taxii', 'use_auth_certificate'):
            self.client.setAuthType(tc.HttpClient.AUTH_CERT_BASIC)
        else:
            self.client.setAuthType(tc.HttpClient.AUTH_NONE)

        self.stix_transformer = StixTransformer(config, data_dir)
开发者ID:RBoutot,项目名称:glastopf,代码行数:32,代码来源:log_taxii.py


注:本文中的ConfigParser.ConfigParser.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。