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


Python ConfigParser.get方法代码示例

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


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

示例1: read_ini_file

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
    def read_ini_file(self,filename):
        cp = ConfigParser()
        cp.read(filename)

        if not self.backup_base_dir:
            self.backup_base_dir = cp.get('global','backup_base_dir')
        if not os.path.isdir(self.backup_base_dir):
            self.logger.info('Creating backup directory %s' % self.backup_base_dir)
            os.makedirs(self.backup_base_dir)

        self.logger.debug("backup directory : " + self.backup_base_dir)
        self.dbstat = BackupStat(os.path.join(self.backup_base_dir,'log','tisbackup.sqlite'))

        for section in cp.sections():
            if (section != 'global'):
                self.logger.debug("reading backup config " + section)
                backup_item = None
                type = cp.get(section,'type')

                backup_item = backup_drivers[type](backup_name=section,
                                                   backup_dir=os.path.join(self.backup_base_dir,section),dbstat=self.dbstat,dry_run=self.dry_run)
                backup_item.read_config(cp)
                backup_item.verbose = self.verbose

                self.backup_list.append(backup_item)
开发者ID:tranquilit,项目名称:TISbackup,代码行数:27,代码来源:tisbackup.py

示例2: checkSSLvdsm

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
    def checkSSLvdsm(self):
        """check if vdsm is running as SSL or without it"""

        cfg = ConfigParser()
        cfg.read('/etc/vdsm/vdsm.conf')
        cfg.get('vars', 'ssl')

        return cfg.data.vars.ssl
开发者ID:dougsland,项目名称:misc-ovirt,代码行数:10,代码来源:forceVMstart.py

示例3: startService

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
    def startService(self):
        cfgpr = ConfigParser()

        # TODO: config location from argparse or something
        cfgpr.read('config/config.ini')
        ip = cfgpr.get('main', 'ip')
        port = cfgpr.getint('main', 'port')
        tag = cfgpr.get('main', 'tag')
        password = cfgpr.get('main', 'password')

        server_data = {
                'ip': ip,
                'port': port,
                'tag': tag, # TODO: what is this:
                'secret': password, # TODO: refactor how this kind of data is passed and stored in factory
                }
        factory = getClientRconFactory(server_data)
        client  = TCPClient(server_data["ip"], server_data["port"], factory)
        client.setServiceParent(self)
        self.server["factory"] = factory
        MultiService.startService(self)
开发者ID:ppolewicz,项目名称:txfbrcon,代码行数:23,代码来源:rconservice.py

示例4: config

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
def config(cfgname, inisect):
    cfg = { }
    cfgpr = ConfigParser()
    try:
        cfgpr.read(cfgname)
        cfg["sleep"] = cfgpr.get(inisect, "sleep")
        cfg["cmd"] = cfgpr.get(inisect, "cmd")
        cfg["file"] = cfgpr.get(inisect, "file")
        cfg["s3mode"] = cfgpr.get(inisect, "s3mode")
        cfg["s3host"] = cfgpr.get(inisect, "s3host")
        cfg["s3user"] = cfgpr.get(inisect, "s3user")
        cfg["s3pass"] = cfgpr.get(inisect, "s3pass")
        cfg["bucket"] = cfgpr.get(inisect, "s3bucket")
        cfg["prefix"] = cfgpr.get(inisect, "prefix")
    except NoSectionError:
        # Unfortunately if the file does not exist, we end here.
        raise ConfigError("Unable to open or find section " + inisect)
    except NoOptionError, e:
        raise ConfigError(str(e))
开发者ID:zaitcev,项目名称:hailcam,代码行数:21,代码来源:hailcamsnap.py

示例5: archive_inv

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
def archive_inv(gameDir, dummyPath, game='FO3', mode=True):
	'''Apply ArchiveInvalidationInvalidated.'''
	if mode:
		if game == 'NV':
			try:
				ini = ConfigParser()
				ini.read(os.environ['USERPROFILE'] + '\\My Games\\FalloutNV\\Fallout.ini')
				ini.set('Archive', 'bInvalidateOlderFiles', '1')
				ini.set('Archive', 'SArchiveList', 'Dummy.bsa,' + ini.get('Archive', 'SArchiveList'))
				
				iniFile = open(os.environ['USERPROFILE'] + '\\My Games\\FalloutNV\\Fallout.ini', 'w')
				ini.write(iniFile)
				
				bsa = open(dummyPath, 'rb').read()
				dummy = open(gameDir + '\\Data\\Dummy.bsa', 'wb')
				dummy.write(bsa)
				dummy.close()
				
				return True
			except IOError:
				return False
开发者ID:Argomirr,项目名称:The-Load-Order-Sorting-Tool,代码行数:23,代码来源:meat.py

示例6: App

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
class App():
    """
    Does all basic events with app
    """
    def __init__(self, appName, critical=None, shortcut='<Control><Q>',
                 quitButton=None, timeout=10, forceKill=True,
                 parameters='', clean_dirs=None, polkit=False):
        """
        Initialize object App
        appName     command to run the app
        critical    what's the function we check? {start,quit}
        shortcut    default quit shortcut
        timeout     timeout for starting and shuting down the app
        forceKill   is the app supposed to be kill before/after test?
        parameters  has the app any params needed to start?
                    (only for startViaCommand)
        """
        self.appCommand = appName.lower()
        self.shortcut = shortcut
        self.timeout = timeout
        self.forceKill = forceKill
        self.critical = critical
        self.quitButton = quitButton
        # the result remains false until the correct result is verified
        self.result = False
        self.updateCorePattern()
        self.parameters = parameters
        self.internCommand = self.appCommand.lower()
        self.polkit = polkit
        self.polkitPass = 'redhat'
        self.clean_dirs = clean_dirs or []

        """
            Getting all necessary data from *.desktop file of the app
        """
        cmd = "rpm -qlf $(which %s)" % appName
        #cmd2 = "grep %s.desktop" % self.appCommand
        #is it enough to search for .desktop?; vhumpa: no
        cmd += '|grep "^/usr/share/applications/.*\%s.desktop$"' % appName
        logging.debug("cmd = %s", cmd)
        proc = Popen(cmd, shell=True, stdout=PIPE)
        #have to check if the command and its desktop file exist
        #raise Exception, "*.desktop file of the app not found"
        #print("*.desktop file of the app not found")
        output = proc.communicate()[0].rstrip()
        logging.debug("output = %s", output)
        self.desktopConfig = ConfigParser()
        self.desktopConfig.read(output)

    def end(self):
        """
        Ends the test with correct return value
        """
        if self.result:
            #print "PASS"
            sys.exit(0)
        else:
            sys.exit("FAIL")

    def updateResult(self, result):
        self.result = result

    def getName(self):
        return self.desktopConfig.get('Desktop Entry', 'name')

    def getCategories(self):
        return self.desktopConfig.get('Desktop Entry', 'categories')

    def getMenuGroups(self):
        """
        Convert group list to the one correct menu group
        """
        groupsList = self.getCategories().split(';')
        groupsList.reverse()
        groupConversionDict = {
            'Accessibility': 'Universal Access',
            'System': 'System Tools',
            'Development': 'Programming',
            'Network': 'Internet',
            'Office': 'Office',
            'Graphics': 'Graphics',
            'Game': 'Games',
            'Education': 'Education',
            'Utility': 'Accessories',
            'AudioVideo': 'Sound &amp; Video'
        }

        for i in groupsList:
            if i in groupConversionDict:
                return groupConversionDict[i]

    def isRunning(self):
        """
        Is the app running?
        """
        #print "*** Checking if '%s' is running" % self.internCommand
        app = root

        apps = root.applications()
        for i in apps:
#.........这里部分代码省略.........
开发者ID:mcepl,项目名称:cucutags,代码行数:103,代码来源:helpers.py

示例7: main

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
def main():
    (options,args)=parser.parse_args()

    if len(args) != 1:
        print "ERROR : You must provide one action to perform"
        parser.print_usage()
        sys.exit(2)

    backup_start_date = datetime.datetime.now().strftime('%Y%m%d-%Hh%Mm%S')

    # options
    action = args[0]
    if action == "listdrivers":
        for t in backup_drivers:
            print backup_drivers[t].get_help()
        sys.exit(0)

    config_file =options.config
    dry_run = options.dry_run
    verbose = options.verbose

    loglevel = options.loglevel

    # setup Logger
    logger = logging.getLogger('tisbackup')
    hdlr = logging.StreamHandler()
    hdlr.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
    logger.addHandler(hdlr)

    # set loglevel
    if loglevel in ('debug','warning','info','error','critical'):
        numeric_level = getattr(logging, loglevel.upper(), None)
        if not isinstance(numeric_level, int):
            raise ValueError('Invalid log level: %s' % loglevel)
        logger.setLevel(numeric_level)

    # Config file
    if not os.path.isfile(config_file):
        logger.error("Error : could not find file : " + config_file + ", please check the path")
    logger.info("Using " + config_file + " config file")

    cp = ConfigParser()
    cp.read(config_file)

    backup_base_dir = options.backup_base_dir or cp.get('global','backup_base_dir')
    log_dir = os.path.join(backup_base_dir,'log')
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)

    # if we run the nagios check, we don't create log file, everything is piped to stdout
    if action!='checknagios':
        hdlr = logging.FileHandler(os.path.join(log_dir,'tisbackup_%s.log' % (backup_start_date)))
        hdlr.setFormatter(logging.Formatter('%(asctime)s %(levelname)s %(message)s'))
        logger.addHandler(hdlr)

    # Main
    backup = tis_backup(dry_run=dry_run,verbose=verbose,backup_base_dir=backup_base_dir)
    backup.read_ini_file(config_file)

    backup_sections = options.sections.split(',') if options.sections else []

    all_sections = [backup_item.backup_name for backup_item in backup.backup_list]
    if not backup_sections:
        backup_sections = all_sections
    else:
        for b in backup_sections:
            if not b in all_sections:
                raise Exception('Section %s is not defined in config file' % b)

    if dry_run:
        logger.warning("WARNING : DRY RUN, nothing will be done, just printing on screen...")

    if action == "backup":
        backup.process_backup(backup_sections)
    elif action == "exportbackup":
        if not options.exportdir:
            raise Exception('No export directory supplied dor exportbackup action')
        backup.export_backups(backup_sections,options.exportdir)
    elif action == "cleanup":
        backup.cleanup_backup_section(backup_sections)
    elif action == "checknagios":
        backup.checknagios(backup_sections)
    elif action == "dumpstat":
        for s in backup_sections:
            backup.dbstat.last_backups(s,count=options.statscount)
    elif action == "retryfailed":
        backup.retry_failed_backups()
    elif action == "register_existing":
        backup.register_existingbackups(backup_sections)


    else:
        logger.error('Unhandled action "%s", quitting...',action)
        sys.exit(1)
开发者ID:tranquilit,项目名称:TISbackup,代码行数:96,代码来源:tisbackup.py

示例8: read_config

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
def read_config():
    config_file = CONFIG[config_number]
    cp = ConfigParser()
    cp.read(config_file)

    backup_base_dir = cp.get('global','backup_base_dir')
    backup = tis_backup(backup_base_dir=backup_base_dir)
    backup.read_ini_file(config_file)

    backup_sections = SECTIONS or []

    all_sections = [backup_item.backup_name for backup_item in backup.backup_list]
    if not backup_sections:
        backup_sections = all_sections
    else:
        for b in backup_sections:
            if not b in all_sections:
                raise Exception('Section %s is not defined in config file' % b)

    result = []
    if not backup_sections:
        sections = [backup_item.backup_name for backup_item in backup.backup_list]

    for backup_item in backup.backup_list:
        if backup_item.backup_name in backup_sections:
            b = {}
            for attrib_name in backup_item.required_params+backup_item.optional_params:
                if hasattr(backup_item,attrib_name):
                    b[attrib_name] = getattr(backup_item,attrib_name)
            result.append(b)

    backup_dict = {}
    backup_dict['rsync_ssh_list'] = []
    backup_dict['rsync_btrfs_list'] = []
    backup_dict['rsync_list'] = []
    backup_dict['null_list'] = []
    backup_dict['pgsql_list'] = []
    backup_dict['mysql_list'] = []
    backup_dict['sqlserver_list'] = []
    backup_dict['xva_list'] = []
    backup_dict['metadata_list'] = []
    backup_dict['switch_list'] = []
    backup_dict['oracle_list'] = []
    for row in result:
        backup_name = row['backup_name']
        server_name = row['server_name']
        backup_type = row['type']
        if backup_type == "xcp-dump-metadata":
            backup_dict['metadata_list'].append([server_name, backup_name, backup_type, ""])
        if backup_type == "rsync+ssh":
            remote_dir = row['remote_dir']
            backup_dict['rsync_ssh_list'].append([server_name, backup_name, backup_type,remote_dir])
        if backup_type == "rsync+btrfs+ssh":
            remote_dir = row['remote_dir']
            backup_dict['rsync_btrfs_list'].append([server_name, backup_name, backup_type,remote_dir])
        if backup_type == "rsync":
            remote_dir = row['remote_dir']
            backup_dict['rsync_list'].append([server_name, backup_name, backup_type,remote_dir])
        if backup_type == "null":
            backup_dict['null_list'].append([server_name, backup_name, backup_type, ""])
	if backup_type == "pgsql+ssh":
	    db_name = row['db_name'] if len(row['db_name']) > 0 else '*'
	    backup_dict['pgsql_list'].append([server_name, backup_name, backup_type, db_name])
	if backup_type == "mysql+ssh":
	    db_name = row['db_name'] if len(row['db_name']) > 0 else '*'
	    backup_dict['mysql_list'].append([server_name, backup_name, backup_type, db_name])
        if backup_type == "sqlserver+ssh":
            db_name = row['db_name']
            backup_dict['sqlserver_list'].append([server_name, backup_name, backup_type, db_name])
        if backup_type == "oracle+ssh":
	    db_name = row['db_name']
	    backup_dict['oracle_list'].append([server_name, backup_name, backup_type, db_name])	    
        if backup_type == "xen-xva":
            backup_dict['xva_list'].append([server_name, backup_name, backup_type, ""])
        if backup_type == "switch":
            backup_dict['switch_list'].append([server_name, backup_name, backup_type, ""])
    return backup_dict
开发者ID:tranquilit,项目名称:TISbackup,代码行数:79,代码来源:tisbackup_gui.py

示例9: ConfigParser

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
import json
import glob
import time

from config import huey 
from tasks import run_export_backup, get_task, set_task

from tisbackup import tis_backup
import logging
import re


cp = ConfigParser()
cp.read("/etc/tis/tisbackup_gui.ini")

CONFIG = cp.get('general','config_tisbackup').split(",")
SECTIONS = cp.get('general','sections')
ADMIN_EMAIL = cp.get('general','ADMIN_EMAIL')

tisbackup_config_file= CONFIG[0]
config_number=0


cp = ConfigParser()
cp.read(tisbackup_config_file)
backup_base_dir = cp.get('global','backup_base_dir')
dbstat = BackupStat(os.path.join(backup_base_dir,'log','tisbackup.sqlite'))
mindate = None
error = None
info = None
app = Flask(__name__)
开发者ID:tranquilit,项目名称:TISbackup,代码行数:33,代码来源:tisbackup_gui.py

示例10: App

# 需要导入模块: from iniparse import ConfigParser [as 别名]
# 或者: from iniparse.ConfigParser import get [as 别名]
class App(object):
    """
    This class does all basic events with the app
    """
    def __init__(
        self, appName, desktopFileName = None, shortcut='<Control><Q>', a11yAppName=None,
            forceKill=True, parameters='', recordVideo=False):
        """
        Initialize object App
        appName     command to run the app
        shortcut    default quit shortcut
        a11yAppName app's a11y name is different than binary
        forceKill   is the app supposed to be kill before/after test?
        parameters  has the app any params needed to start? (only for startViaCommand)
        recordVideo start gnome-shell recording while running the app
        """
        self.appCommand = appName
        self.shortcut = shortcut
        self.forceKill = forceKill
        self.parameters = parameters
        self.internCommand = self.appCommand.lower()
        self.a11yAppName = a11yAppName
        self.recordVideo = recordVideo
        self.pid = None
        if desktopFileName is None:
            desktopFileName = self.appCommand
        self.desktopFileName = desktopFileName
        # a way of overcoming overview autospawn when mouse in 1,1 from start
        pressKey('Esc')
        absoluteMotion(100, 100, 2)

        # attempt to make a recording of the test
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')

    def isRunning(self):
        """
        Is the app running?
        """
        if self.a11yAppName is None:
            self.a11yAppName = self.internCommand

        # Trap weird bus errors
        for attempt in xrange(0, 30):
            sleep(1)
            try:
                return self.a11yAppName in [x.name for x in root.applications()]
            except GLib.GError:
                continue
        raise Exception("10 at-spi errors, seems that bus is blocked")

    def getDashIconPosition(name):
        """Get a position of miniature on Overview"""
        over = root.application('gnome-shell').child(name='Overview')
        button = over[2].child(name=name)
        (x, y) = button.position
        (a, b) = button.size
        return (x + a / 2, y + b / 2)
    
    def parseDesktopFile(self):
        """
        Getting all necessary data from *.dektop file of the app
        """
        cmd = "rpm -qlf $(which %s)" % self.appCommand
        cmd += '| grep "^/usr/share/applications/.*%s.desktop$"' % self.desktopFileName
        proc = Popen(cmd, shell=True, stdout=PIPE)
        # !HAVE TO check if the command and its desktop file exist
        if proc.wait() != 0:
            raise Exception("*.desktop file of the app not found")
        output = proc.communicate()[0].rstrip()
        self.desktopConfig = ConfigParser()
        self.desktopConfig.read(output)
    
    def kill(self):
        """
        Kill the app via 'killall'
        """
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')

        try:
            self.process.kill()
        except:
            # Fall back to killall
            Popen("killall " + self.appCommand, shell=True).wait()

    def getName(self):
        return self.desktopConfig.get('Desktop Entry', 'name')

    def startViaCommand(self):
        """
        Start the app via command
        """
        if self.forceKill and self.isRunning():
            self.kill()
            sleep(2)
            assert not self.isRunning(), "Application cannot be stopped"

        self.process = Popen(self.appCommand.split() + self.parameters.split(),
                             stdout=PIPE, stderr=PIPE, bufsize=0)
#.........这里部分代码省略.........
开发者ID:shivanipoddariiith,项目名称:evince,代码行数:103,代码来源:behave_common_steps.py

示例11: App

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

    """
    Does all basic events with app
    """

    def __init__(
        self, appName, critical=None, shortcut='<Control><Q>', desktopFileName=None, a11yAppName=None, quitButton=None, timeout=5,
            forceKill=True, parameters='', polkit=False, recordVideo=True):
        """
        Initialize object App
        appName     command to run the app
        critical    what's the function we check? {start,quit}
        shortcut    default quit shortcut
        timeout     timeout for starting and shuting down the app
        forceKill   is the app supposed to be kill before/after test?
        parameters  has the app any params needed to start? (only for startViaCommand)
        desktopFileName = name of the desktop file if other than appName (without .desktop extension)
        """
        self.appCommand = appName
        self.shortcut = shortcut
        self.timeout = timeout
        self.forceKill = forceKill
        self.critical = critical
        self.quitButton = quitButton
        # the result remains false until the correct result is verified
        self.result = False
        self.updateCorePattern()
        self.parameters = parameters
        self.internCommand = self.appCommand.lower()
        self.polkit = polkit
        self.polkitPass = 'redhat'
        self.a11yAppName = a11yAppName
        self.recordVideo = recordVideo

        if desktopFileName is None:
            desktopFileName = self.appCommand
        self.desktopFileName = desktopFileName

        # a way of overcoming overview autospawn when mouse in 1,1 from start
        pressKey('Esc')
        absoluteMotion(100, 100, 2)
        # attempt to make a recording of the test
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')

    def parseDesktopFile(self):
        """
        Getting all necessary data from *.dektop file of the app
        """
        cmd = "rpm -qlf $(which %s)" % self.appCommand
        cmd += '| grep "^/usr/share/applications/.*%s.desktop$"' % self.desktopFileName
        proc = Popen(cmd, shell=True, stdout=PIPE)
        # !HAVE TO check if the command and its desktop file exist
        if proc.wait() != 0:
            raise Exception("*.desktop file of the app not found")
        output = proc.communicate()[0].rstrip()
        self.desktopConfig = ConfigParser()
        self.desktopConfig.read(output)

    def end(self):
        """
        Ends the test with correct return value
        """
        if self.recordVideo:
            keyCombo('<Control><Alt><Shift>R')
        time.sleep(2)
        if not isProcessRunning('gnome-shell') or isProcessRunning('gnome-shell --mode=gdm'):
            print ("Error: gnome-shell/Xorg crashed during or after the test!")
            self.result = False

        if self.result:
            print("PASS")
            sys.exit(0)
        else:
            print("FAIL")
            sys.exit(1)

    def updateResult(self, result):
        self.result = result

    def getName(self):
        return self.desktopConfig.get('Desktop Entry', 'name')

    def getExec(self):
        try:
            return (
                self.desktopConfig.get(
                    'Desktop Entry',
                    'exec').split()[0].split('/')[-1]
            )
        except ConfigParser.NoOptionError:
            return self.getName()

    def getCategories(self):
        return self.desktopConfig.get('Desktop Entry', 'categories')

    def getMenuGroups(self):
        """
        Convert group list to the one correct menu group
#.........这里部分代码省略.........
开发者ID:fedora-desktop-tests,项目名称:dogtail_gui_helper,代码行数:103,代码来源:gnome_apps_helper.py


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