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


Python ConfigParser.read方法代码示例

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


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

示例1: main

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [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

示例2: getDataSources

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
def getDataSources(fName = None):
    ''' return data sources directories for this machine.
    directories are defined in datasources.ini or provided filepath'''
    import socket
    from ConfigParser import ConfigParser

    pcName = socket.gethostname()

    p = ConfigParser()
    p.optionxform = str


    if fName is None:
        fName = 'datasources.ini'

    p.read(fName)

    if pcName not in p.sections():
        raise NameError('Host name section %s not found in file %s' %(pcName,fName))

    dataSources = {}
    for option in p.options(pcName):
        dataSources[option] = p.get(pcName,option)

    return dataSources
开发者ID:hezhenke,项目名称:myIbPy,代码行数:27,代码来源:functions.py

示例3: ConfigLoader

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
class ConfigLoader():
    def __init__(self):
        try:
            open(cfg_name, 'r').close()
        except:
            sys.stderr.write(u'严重错误,无法读取配置文件!程序自动退出。\n')
            exit(-1)
        self.config = ConfigParser()
        self.config.read(cfg_name)
        self.system = dict(self.config.items('system'))
        self.config_check()

    def config_check(self):
        try:
            # 首先检查设定的全局存储目录是否合法
            check_path(self.read('global_pos'))
            # 然后检查管理员的下载目录是否存在
            root_path = os.path.join(self.read('global_pos'), 'root')
            if not os.path.exists(root_path):
                os.mkdir(root_path)
        except Exception, err:
            sys.stderr.write(u'系统错误,原因:%s\n' % err)
            exit(-1)
        # 接下来检查端口是否可用
        if check_port(self.read('port_name')):
            sys.stderr.write(u'系统错误,端口被占用!\n')
            exit(-1)
开发者ID:FinalTheory,项目名称:PicDownloader,代码行数:29,代码来源:Tools.py

示例4: Config

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

	def __init__(self):
		self.parser = ConfigParser()
		self.read_configuration()

	def read_configuration(self):
		# check if we are in svn working dir
		if not os.path.isdir('.svn'):
			raise ExsvnError("Current directory is not a svn working directory")

		fullcfgname = os.path.join('.svn', CONFIG_FILENAME)
		if not os.path.exists(fullcfgname):
			self.create_configuration(fullcfgname)
		
		self.parser.read(fullcfgname)

	def create_configuration(self, fname):
		"""Create new configuration file"""
		print "Creating default configuration in %s" % fname
		cfg = self.get_default_configuration()

		f = file(fname, "w")
		f.write(cfg)
		f.close()

		# protect from others
		os.chmod(fname, 0600)

	def get_default_configuration(self):
		return """
开发者ID:kedder,项目名称:exsvn,代码行数:33,代码来源:config.py

示例5: Config

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
class Config(object):
    def __new__(type, *args, **kwargs):
        if not '_the_instance' in type.__dict__:
            type._the_instance = object.__new__(type)
        return type._the_instance
    
    def __init__(self, filename = None):
        if filename != None:
            self.filename = filename
            self.config = ConfigParser()
            self.config.read(self.filename)
    
    def get_section(self,name):
        if self.config.has_section(name):
            return _Section(name, self.config.items(name), self)
        else:
            return _Section(name, [], self)
    
    def __getattr__(self, attr):
        if attr == 'irc':
            return self.get_section('IRC')
        elif attr == 'ldap':
            return self.get_section('LDAP')
        elif attr == 'rpc':
            return self.get_section('RPC')
        elif attr == 'bot':
            return self.get_section('Bot')
        elif attr == 'smtp':
            return self.get_section('SMTP')
        elif attr == 'db':
            return self.get_section('Database')
        elif attr == 'identica':
            return self.get_section('Identi.ca')
        else:
            raise AttributeError('No section \'%s\' in Config.' % attr)
开发者ID:miri64,项目名称:spline_social,代码行数:37,代码来源:config.py

示例6: process_config

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
def process_config(directory, config_file, sp):
	
	config = ConfigParser()
	config.read(config_file)
	sections = config.sections()
	
	db_or_element = db_or_element_format(sp, sections)
	
	if db_or_element == "db":
		invalid_sections = fc.invalid_config_sections(directory, config_file, sp.full_header_data("db"))
	elif db_or_element == "element":
		invalid_sections = fc.invalid_config_sections(directory, config_file, sp.full_header_data("element"))
	else:
		return "error"

	for s in sections:
		fname = config.get(s, "file_name")
		header = config.get(s, "header")
		if s in invalid_sections:
			if os.path.exists(directory + fname):
				os.remove(directory + fname)
		else:
			with open(directory + s + "_temp.txt", "w") as w:
				w.write(header + "\n")
				with open(directory + fname, "r") as r:
					for line in r:
						w.write(line)
				os.remove(directory + fname)
			os.rename(directory + s + "_temp.txt", directory + fname)
	os.remove(config_file)
	if len(invalid_sections) == 0:
		return None
	return {"invalid_sections":invalid_sections}
开发者ID:simbha,项目名称:VAVE,代码行数:35,代码来源:feed_destructor.py

示例7: getMysqlConfig

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [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

示例8: restore_rois

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
    def restore_rois(self, roifile):
        """restore ROI setting from ROI.dat file"""
        cp =  ConfigParser()
        cp.read(roifile)
        rois = []
        self.mcas[0].clear_rois()
        prefix = self.mcas[0]._prefix
        if prefix.endswith('.'):
            prefix = prefix[:-1]
        iroi = 0
        for a in cp.options('rois'):
            if a.lower().startswith('roi'):
                name, dat = cp.get('rois', a).split('|')
                lims = [int(i) for i in dat.split()]
                lo, hi = lims[0], lims[1]
                roi = ROI(prefix=prefix, roi=iroi)
                roi.left = lo
                roi.right = hi
                roi.name = name.strip()
                rois.append(roi)
                iroi += 1

        epics.poll(0.050, 1.0)
        self.mcas[0].set_rois(rois)
        cal0 = self.mcas[0].get_calib()
        for mca in self.mcas[1:]:
            mca.set_rois(rois, calib=cal0)
开发者ID:robinliheyi,项目名称:pyepics,代码行数:29,代码来源:mca.py

示例9: _load_configuration

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
def _load_configuration(environment, path):
        """Loads a given configuration file specified by path and environment header (ini file).
        returns a key value representing the configuration. Values enclosed in {} are automatically
        decrypted using the $FURTHER_PASSWORD variable. Values that equal [RND] will be replaced with
        a random string."""

        # Read configuration file
        parser = ConfigParser()
        parser.read(path)

        config = {}
        for option in parser.options(environment):
                value = parser.get(environment, option)

                # Handle encrypted configuration
                if (re.match(r'^\{.*\}$', value)):
                        encrypted_value = re.match(r'^\{(.*)\}$', value).group(1)
                        value = (local('decrypt.sh input="' + encrypted_value + '" password=$FURTHER_PASSWORD algorithm="PBEWithSHA1AndDESede" verbose="false"', capture=True))

                # Handle random values
                if (re.match(r'\[RND\]', value)):
                        value = _random_string()

                config[option] = value;

        return config
开发者ID:openfurther,项目名称:further-open-fabric-deployment,代码行数:28,代码来源:deployment.py

示例10: test_import_local

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
    def test_import_local(self):
        self.tool.run(
            config=(self.yaml_config, self.config),
            verbose=True,
            clobber=False,
            repo_dir=self.working_dir,
            repo_url=self.workspace.working_dir,
            ini_config=self.ini_config,
            ini_section='app:main',
            update_config=True,
            repo_name=None,
            repo_host=None)

        cp = ConfigParser()
        cp.read(self.ini_config)
        self.assertEqual(
            cp.get('app:main', 'unicore.content_repo_urls').strip(),
            os.path.basename(self.workspace.working_dir))

        with open(self.yaml_config, 'r') as fp:
            data = yaml.safe_load(fp)
            repo_name = parse_repo_name(self.workspace.working_dir)
            self.assertEqual(data['repositories'], {
                repo_name: self.workspace.working_dir
            })
开发者ID:universalcore,项目名称:springboard,代码行数:27,代码来源:test_tools.py

示例11: test_import_remote

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
    def test_import_remote(self):
        repo_name = parse_repo_name(self.workspace.working_dir)
        repo_location = 'http://localhost:8080/repos/%s.json' % repo_name
        responses.add_callback(
            responses.POST,
            'http://localhost:8080/repos.json',
            callback=lambda _: (301, {'Location': repo_location}, ''))

        self.tool.run(
            config=(self.yaml_config, self.config),
            verbose=True,
            clobber=False,
            repo_dir=self.working_dir,
            repo_url=self.workspace.working_dir,
            ini_config=self.ini_config,
            ini_section='app:main',
            update_config=True,
            repo_name=None,
            repo_host='http://localhost:8080')

        cp = ConfigParser()
        cp.read(self.ini_config)
        self.assertEqual(
            cp.get('app:main', 'unicore.content_repo_urls').strip(),
            repo_location)

        with open(self.yaml_config, 'r') as fp:
            data = yaml.safe_load(fp)
            self.assertEqual(data['repositories'], {
                repo_name: self.workspace.working_dir
            })
开发者ID:universalcore,项目名称:springboard,代码行数:33,代码来源:test_tools.py

示例12: _set_config_all

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [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

示例13: initConfig

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
    def initConfig(self):
        kate.debug("initConfig()")
        config_path = kate.pate.pluginDirectories[1] + "/%s/%s.conf" % (__name__, __name__)
        config_file = QFileInfo(config_path)

        if not config_file.exists():
            open(config_path, "w").close()

        config = ConfigParser()
        config.read(config_path)

        # init the DEFAULT options if they don't exist
        # the DEFAULT section is special and doesn't need to be created: if not config.has_section('DEFAULT'): config.add_section('DEFAULT')
        if not config.has_option("DEFAULT", "ignore"):
            config.set("DEFAULT", "ignore", "")
        if not config.has_option("DEFAULT", "filter"):
            config.set("DEFAULT", "filter", "*")
        if not config.has_option("DEFAULT", "finder_size"):
            config.set("DEFAULT", "finder_size", "400x450")
        if not config.has_option("DEFAULT", "config_size"):
            config.set("DEFAULT", "config_size", "300x350")
        if not config.has_option("DEFAULT", "search_type"):
            config.set("DEFAULT", "search_type", "word")

        # create the general section if it doesn't exist
        if not config.has_section("general"):
            config.add_section("general")

        # flush the config file
        config.write(open(config_path, "w"))

        # save the config object and config path as instance vars for use later
        self.config = config
        self.config_path = config_path
开发者ID:jorrel,项目名称:kate_directory_project,代码行数:36,代码来源:directory_project.py

示例14: start

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
    def start(self):
        from scheduler import Tree

        loog = self.addLog("stdio")
        self.pending = 0
        properties = self.build.getProperties()
        self.rendered_tree = tree = properties.render(self.treename)
        l10nbuilds = properties.render(self.l10nbuilds)
        cp = ConfigParser()
        cp.read(l10nbuilds)
        repo = cp.get(tree, "repo")
        branch = cp.get(tree, "mozilla")
        path = cp.get(tree, "l10n.ini")
        l10nbranch = cp.get(tree, "l10n")
        locales = cp.get(tree, "locales")
        if locales == "all":
            alllocales = "yes"
        else:
            alllocales = "no"
            properties.update({"locales": filter(None, locales.split())}, "Build")
        self.tree = Tree(self.rendered_tree, repo, branch, l10nbranch, path)
        loog.addStdout("Loading l10n.inis for %s\n" % self.rendered_tree)
        logger.debug(
            "scheduler.l10n.tree", "Loading l10n.inis for %s, alllocales: %s" % (self.rendered_tree, alllocales)
        )
        self.loadIni(repo, branch, path, alllocales)
开发者ID:pombredanne,项目名称:locale-inspector,代码行数:28,代码来源:steps.py

示例15: getConfig

# 需要导入模块: from ConfigParser import ConfigParser [as 别名]
# 或者: from ConfigParser.ConfigParser import read [as 别名]
	def getConfig(self):
		self.cursor.execute("SELECT name, host, port, account, account_password, base_dn, attr_login, attr_firstname, attr_lastname, attr_mail, tls FROM auth_sources")
		self.results = self.cursor.fetchall()
		dic = {}
		if self.results <> ():
			for i in range(0,11):
				dic[ self.indice[ ( i ) ] ] = self.results[0][i]
			dic["fonte_config"] = "redmine"
			return dic
		else:
			for i in self.indice:
				dic[ i ] = "Sem regsitro"
			from ConfigParser import ConfigParser
			conf = ConfigParser()
			conf.read('/etc/ldap/netcontrol')
			dic["nomeServidor"] = conf.get('base','organization')
			dic["enderecoServidor"] = conf.get('base','server')
			dic["contaLDAP"]        = "cn=admin,%s"%conf.get('base','bindDN')
			dic["baseDN"]           = conf.get('base','bindDN')
			dic["senhaContLDAP"]    = conf.get('base','adminPW')
			dic["email"]     		= conf.get('base','email')
			dic["porta"]			= "389"
			dic["usuario"]	    	= "uid"
			dic["nomeUser"]			= "giverName"
			dic["sobrenome"]		= "sN"
			dic["fonte_config"] = "arquivo_ldap"
			del conf
		return dic
开发者ID:GabrielDiniz,项目名称:FluxNetControl,代码行数:30,代码来源:backend.py


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