Пример #1
0
    def __init__(self, cliargs=None, **kwargs):
        defaults = cliargs or {}
        for k in [k for k in defaults.keys() if not defaults[k]]:
            del defaults[k]

        defaults.setdefault('socket-path', '/run/amavisvtd.sock')

        defaults.setdefault('positive-expire', str(21 * 86400))
        defaults.setdefault('negative-expire', str(12 * 3600))
        defaults.setdefault('unknown-expire', str(12 * 3600))
        defaults.setdefault('timeout', '10')
        defaults.setdefault('hits-required', "5")
        defaults.setdefault('pretend', 'false')
        defaults.setdefault('api-url', "https://www.virustotal.com/vtapi/v2/file/report")
        defaults.setdefault('report-url', "https://www.virustotal.com/vtapi/v2/file/scan")
        defaults.setdefault('database-path', '/var/lib/amavisvt/amavisvt.sqlite3')

        defaults.setdefault('filename-pattern-detection', 'false')
        defaults.setdefault('min-filename-patterns', '20')
        defaults.setdefault('infected-percent', '0.7')
        defaults.setdefault('auto-report', 'false')

        ConfigParser.__init__(self, defaults=defaults)
        paths = kwargs.get('path', None)
        if paths:
            paths = [paths]
        else:
            paths = [
                '/etc/amavisvt.cfg',
                os.path.expanduser('~/.amavisvt.cfg'),
                'amavisvt.cfg'
            ]
        files_read = self.read(paths)
        logger.info("Read configuration files: %s", files_read)
Пример #2
0
 def __init__(self, piefolder=None, headerfile=None):
     SafeConfigParser.__init__(self)
     assert piefolder or headerfile
     if piefolder:
         assert type(piefolder) == PieFolder
         assert piefolder.initialised == 1
     if piefolder:
         self.add_section(_('Folder Information'))
         self.set(_('Folder Information'), 
                  _('Name'), piefolder.EndName.encode('utf8'))
         self.set(_('Folder Information'), 
                  _('Area'), piefolder.Root.encode('utf8'))
         self.set(_('Folder Information'), 
                  _('Record System No.'), 
                  piefolder.RecordFile.encode('utf8'))
         self.set(_('Folder Information'), 
                  _('Security Level'), 
                  SECURITY_CLASSES[piefolder.SecurityLevel])
         self.path = piefolder.path()
     elif headerfile:
         assert os.path.isfile(headerfile)
         self.read(headerfile)
     self.recordfile = self.get(_('Folder Information'), 
                                _('Record System No.'))
     self.securitylevel = self.get(_('Folder Information'),
                                   _('Security Level'))
Пример #3
0
    def __init__(self):
        # enforce singleton pattern
        if(not Configuration.__configuration == None):
            raise Configuration.__configuration
        Configuration.__configuration = self

        SafeConfigParser.__init__(self)

        # get a logger
        self.__logger = logging.getLogger("chattest.server.Configuration")
        self.__logger.debug("Created a new Configuration object...")

        # create the default sections
        self.add_section("network")
        self.add_section("database")
        self.add_section("miscellaneous")
        self.add_section("telnet")

        # set the default values
        self.set("miscellaneous", "daemon", "true")
        self.set("miscellaneous", "ping", "1")
        self.set("miscellaneous", "timeout", "5")
        self.set("network", "port", "8376")
        self.set("database", "type", "local")
        self.set("database", "host", "localhost")
        self.set("database", "database", "chattest")
        self.set("database", "user", "root")
        self.set("database", "password", "password")
        self.set("telnet", "port", "8377")
        self.set("telnet", "user", "telnet")
        self.set("telnet", "password", "telnet")
Пример #4
0
    def __init__(self, defaults=global_defaults, configfile=None):
        self.__dict__ = self.__shared_state
        if getattr(self, "baseconfig", None):
            if not configfile or self.baseconfig == os.path.realpath(configfile):
                return
            raise AquilonError("Could not configure with %s, already "
                               "configured with %s" %
                               (configfile, self.baseconfig))
        # This is a small race condition here... baseconfig could be
        # checked here, pre-empted, checked again elsewhere, and also
        # get here.  If that ever happens, it is only a problem if one
        # passed in a configfile and the other didn't.  Punting for now.
        if configfile:
            self.baseconfig = os.path.realpath(configfile)
        else:
            self.baseconfig = os.path.realpath(os.environ.get("AQDCONF",
                                                              "/etc/aqd.conf"))
        SafeConfigParser.__init__(self, defaults)
        src_defaults = lookup_file_path("aqd.conf.defaults")
        read_files = self.read([src_defaults, self.baseconfig])
        for file in [src_defaults, self.baseconfig]:
            if file not in read_files:
                raise AquilonError("Could not read configuration file %s." % file)

        # Allow a section to "pull in" another section, as though all the
        # values defined in the alternate were actually defined there.
        for section in self.sections():
            section_option = "%s_section" % section
            if self.has_option(section, section_option):
                alternate_section = self.get(section, section_option)
                if self.has_section(alternate_section):
                    for (name, value) in self.items(alternate_section):
                        self.set(section, name, value)
Пример #5
0
	def __init__(self, defaults = {}, types = {}):
		"""Constructor.
			If any filenames given tries to parse them
			Input: (string) filename. You can pass pultiple file names
				(dict) defaults: {'section': {'attrib': 'value'}},
				(dict) types: {'section': {'attrib': 'type'}}; types supported are:
					int, str, string, float, bool; default: string
			Output: (Config) class instance
		"""
		# call base class constructors
		SafeConfigParser.__init__(self)
		#UserDict.__init__(self)
		
		### IMPORTANT!!! Link self.data to self._sections to provide connectivity between UserDict and SafeConfigParser
		self.data = self._sections
		self._types = types
		self._defaultOptions = defaults
		self._rawData = {}
		
		for (section, attributes) in defaults.items():
			section = str(section)
			if not self.has_section(section):
				self.add_section(section)
			for (key, value) in attributes.items():
				key = self.optionxform(str(key))
				self.set(section, key, value)
Пример #6
0
 def __init__(self):
     self._log = logging.getLogger('%s.%s' %
                                   (__name__, self.__class__.__name__))
     self._log.addHandler(NullHandler.NullHandler())
     SafeConfigParser.__init__(self)
     self.add_section('scoreboard')
     self.set('scoreboard', 'errors', "ERROR")
     self.set('scoreboard', 'warnings', "WARNING WARN")
     self.set('scoreboard', 'test_begin', "TEST_BEGIN")
     self.set('scoreboard', 'test_end', "TEST_END")
     #        logging.error("HERE IS AN ERROR")
     #        self.logger = logging.getLogger(__name__)
     #        self.logger.addHandler(NullHandler.NullHandler())
     #        logging.getLogger(__name__).addHandler(NullHandler.NullHandler())
     self.rc_files = []
     self.successful_rc_files = []
     if (sys.platform in unix_plats):
         self.rc_files = [
             '/etc/simshop/simshoprc',
             os.path.normpath(os.path.expanduser("~") + "/.simshoprc"),
         ]
     elif (sys.platform in win_plats):
         self.rc_files = [
             os.path.normpath(os.environ['ALLUSERSPROFILE'] + "/simshoprc"),
             os.path.normpath(os.environ['USERPROFILE'] + "/simshoprc"),
         ]
Пример #7
0
    def __init__(self):
        self._log = logging.getLogger('%s.%s' % (__name__, self.__class__.__name__))
        self._log.addHandler(NullHandler.NullHandler())
        SafeConfigParser.__init__(self)
        self.add_section('scoreboard')
        self.set('scoreboard', 'errors', "ERROR")
        self.set('scoreboard', 'warnings', "WARNING WARN")
        self.set('scoreboard', 'test_begin', "TEST_BEGIN")
        self.set('scoreboard', 'test_end', "TEST_END")
#        logging.error("HERE IS AN ERROR")
#        self.logger = logging.getLogger(__name__)
#        self.logger.addHandler(NullHandler.NullHandler())
#        logging.getLogger(__name__).addHandler(NullHandler.NullHandler())
        self.rc_files = []
        self.successful_rc_files = []
        if(sys.platform in unix_plats):
            self.rc_files = [
                                '/etc/simshop/simshoprc',
                                os.path.normpath(os.path.expanduser("~")  + "/.simshoprc"),
                             ]
        elif(sys.platform in win_plats):
            self.rc_files = [
                                os.path.normpath(os.environ['ALLUSERSPROFILE'] + "/simshoprc"),
                                os.path.normpath(os.environ['USERPROFILE'] + "/simshoprc"),
                             ]
Пример #8
0
 def __init__(self, path):
     # with open(path, 'r') as cfg_file:
     #     cfg_txt = os.path.expandvars(cfg_file.read())
     #     SafeConfigParser.__init__(self)
     #     self.readfp(StringIO.StringIO(cfg_txt))
     SafeConfigParser.__init__(self, os.environ)
     self.read(path)
Пример #9
0
    def __init__(self, filename):
        # Do singleton checking.
        if Config.INSTANCE != None:
            raise Exception('Singleton error: an instance of Config already exists.')
        
        # Create the parent dir if it does not exist.
        if not os.path.exists(filename):
            dirname = os.path.dirname(filename) 
            if dirname != '':
                os.mkdir(dirname)

        # Initialize the config by reading in the file and then checking if 
        # standard values must be plugged in...
        SafeConfigParser.__init__(self)
        self._filename = filename
        self.read(self._filename)
        self._dirty = False
        self.set_defaults()
        
        # Write the config file if necessary.
        if self._dirty:
            with open(self._filename, 'wb') as configfile:
                self.write(configfile)
                self._dirty = False

        # Set the singleton pointer.
        Config.INSTANCE = self
Пример #10
0
    def __init__(self, request):
        # Note that SafeConfigParser if not a new class so we have to explicitly
        # call the __init__method
        SafeConfigParser.__init__(self)
        
        try:
            host = request.session['host']
            username = request.session['username'] 
            user_conf = os.path.join(settings.USERCONFDIR, '%s@%s.conf' % (username,host))

            if not os.path.isfile(user_conf): # Touch the user configuration file
                open(user_conf, 'w').close()

            server_conf = os.path.join(settings.SERVERCONFDIR, '%s.conf' % host )

            config_files =  [ settings.FACTORYCONF,
                              settings.DEFAULTCONF,
                              user_conf,
                              server_conf,
                              settings.SYSTEMCONF ]
        except KeyError:
            config_files = [ settings.FACTORYCONF,
                             settings.DEFAULTCONF ]

        self.read( config_files )
Пример #11
0
    def __init__(self, file='C:\plexus\config.ini', part_number="",hwrev="",ccode="", operatorID="", mac="",product="" ):
        SafeConfigParser.__init__(self)

        if os.path.isfile( file ):
            self.no_log = False
        else:
            self.no_log = True
            print "PlexusLog config file not found: %s" % file
        
        self.file = file
        self.read(file)
        logging.debug("loading: %s " % self.file)
        self.operatorID = operatorID
        self.mac = ''.join(mac)

        self.AssemblyNo = "113-%s-%s-%s" % ( part_number, hwrev, ccode)
        self.FixtureID = self.get_data('Datalog','FixtureID','NoFixture')
        self.SystemID = self.get_data('Datalog','SystemID','NoSystemID')
        self.Extension = self.get_data('Datalog','Extension','NoExtension')
        self.EventTyp  = self.get_data('Datalog','EventTyp','NoEventTyp')
        self.ProcessTyp = self.get_data('Datalog','ProcessTyp','NoProcessTyp')
#        self.TestSystemID = self.get_data('Datalog','TestSystemID','NoTestSystemID')
        self.CustomerID = self.get_data('Datalog','CustomerID','NoCustomerID')
        self.EcRevLvl = hwrev
        self.product = product
        self.TestSystemID = self.product + self.ProcessTyp + self.SystemID
        default_path = file.replace('config.ini','Log')
        self.Result_path = self.get_data('Path','Result_path', default_path)
        if os.path.isdir( self.Result_path ) == False:
            self.no_log = True
            print "PlexusLog path not found: %s" % self.Result_path
Пример #12
0
    def __init__(self, cliargs=None, **kwargs):
        defaults = cliargs or {}
        for k in [k for k in defaults.keys() if not defaults[k]]:
            del defaults[k]

        defaults.setdefault("socket-path", "/run/amavisvtd.sock")

        defaults.setdefault("positive-expire", str(21 * 86400))
        defaults.setdefault("negative-expire", str(12 * 3600))
        defaults.setdefault("unknown-expire", str(12 * 3600))
        defaults.setdefault("timeout", "10")
        defaults.setdefault("hits-required", "5")
        defaults.setdefault("pretend", "false")
        defaults.setdefault("api-url", "https://www.virustotal.com/vtapi/v2/file/report")
        defaults.setdefault("report-url", "https://www.virustotal.com/vtapi/v2/file/scan")
        defaults.setdefault("database-path", "/var/lib/amavisvt/amavisvt.sqlite3")

        defaults.setdefault("filename-pattern-detection", "false")
        defaults.setdefault("min-filename-patterns", "20")
        defaults.setdefault("infected-percent", "0.7")
        defaults.setdefault("auto-report", "false")

        ConfigParser.__init__(self, defaults=defaults)
        paths = kwargs.get("path", None)
        if paths:
            paths = [paths]
        else:
            paths = ["/etc/amavisvt.cfg", os.path.expanduser("~/.amavisvt.cfg"), "amavisvt.cfg"]
        files_read = self.read(paths)
        logger.info("Read configuration files: %s", files_read)
Пример #13
0
        def __init__(self, env):
                SafeConfigParser.__init__(self)
                self._updated = {}
                self.env = env

                if os.path.exists(self._userconfigfile):
                        self.read(self._userconfigfile)
                elif os.path.exists(self._globalconfigfile):
                        self.read(self._globalconfigfile)
                else:
                        SafeConfigParser.set(self, "general", "threshold_timeout", "5")
                        SafeConfigParser.set(self, "general", "x11_idle_timeout", "5")
                        SafeConfigParser.set(self, "idmef", "profile", "requiem-notify")
                        SafeConfigParser.set(self, "idmef", "filter", "")
                        SafeConfigParser.set(self, "manager", "addresses", "127.0.0.1")
                        SafeConfigParser.set(self, "confutatis", "url", "http://localhost:8000")
                        SafeConfigParser.set(self, "ui", "theme", "default")
                        SafeConfigParser.set(self, "ui", "browser", "auto")



		_configtheme = SafeConfigParser.get(self,"ui","theme")

		if os.path.isdir( userthemespath + "/" + _configtheme ):
			self.theme = userthemespath + "/" + _configtheme
		elif os.path.isdir( globalthemespath + "/" +  _configtheme ):
			self.theme = globalthemespath + "/" + _configtheme
		else:
			self.theme = globalthemespath + "/" + "default"
Пример #14
0
 def __init__(self, server, fd):
     """"""
     SafeConfigParser.__init__(self)
     self.readfp(fd)
     self.server = server
     self.version = self.get(SECTION_MAIN, OPTION_VERSION)
     self.services = self.items(SECTION_UPDATES)
Пример #15
0
    def __init__(self, files=None, keep_dashes=True):
        """Initialize

        files[in]       The files to parse searching for configuration items.
        keep_dashes[in] If False, dashes in options are replaced with
                        underscores.

        Raises ValueError if defaults is set to True but defaults files
        cannot be found.
        """

        # Regular expression to allow options with no value(For Python v2.6)
        self.OPTCRE = re.compile(           # pylint: disable=C0103
            r'(?P<option>[^:=\s][^:=]*)'
            r'\s*(?:'
            r'(?P<vi>[:=])\s*'
            r'(?P<value>.*))?$'
        )

        self._options_dict = {}

        SafeConfigParser.__init__(self)
        self.default_extension = DEFAULT_EXTENSIONS[os.name]
        self.keep_dashes = keep_dashes

        if not files:
            raise ValueError('files argument should be given')
        if isinstance(files, str):
            self.files = [files]
        else:
            self.files = files

        self._parse_options(list(self.files))
        self._sections = self.get_groups_as_dict()
Пример #16
0
 def __init__(self, conf):
     """"""
     SafeConfigParser.__init__(self)
     self.read(conf)
     if self.has_section("pages"):
         for option in self.options("pages"):
             if self.has_section(option):
                 css = None
                 if self.has_option(option, "css"):
                     css = self.get(option, "css")
                 t = Template(self.get(option, "title"), css)
                 advanced_options = []
                 if self.has_option(option, "advanced"):
                     advanced = self.get(option, "advanced")
                     if self.has_section(advanced):
                         for advanced_option in self.options(advanced):
                             tmp = [
                                 advanced_option,
                                 self.get(advanced, advanced_option)
                             ]
                             if self.has_section(advanced_option):
                                 tmp.append(self.items(advanced_option))
                             advanced_options.append(tmp)
                 t.add_content(option, advanced_options)
                 t.save(self.get("pages", option))
Пример #17
0
    def __init__(self):
        SafeConfigParser.__init__(self)

        self.add_section('pungi')

        self.set('pungi', 'osdir', 'os')
        self.set('pungi', 'sourcedir', 'source')
        self.set('pungi', 'debugdir', 'debug')
        self.set('pungi', 'isodir', 'iso')
        self.set('pungi', 'relnotefilere',
                 'GPL README-BURNING-ISOS-en_US.txt ^RPM-GPG')
        self.set('pungi', 'relnotedirre', '')
        self.set('pungi', 'relnotepkgs', 'fedora-release fedora-release-notes')
        self.set('pungi', 'product_path', 'Packages')
        self.set('pungi', 'cachedir', '/var/cache/pungi')
        self.set('pungi', 'compress_type', 'xz')
        self.set('pungi', 'arch', yum.rpmUtils.arch.getBaseArch())
        self.set('pungi', 'name', 'Fedora')
        self.set('pungi', 'iso_basename', 'Fedora')
        self.set('pungi', 'version', time.strftime('%Y%m%d', time.localtime()))
        self.set('pungi', 'flavor', '')
        self.set('pungi', 'destdir', os.getcwd())
        self.set('pungi', 'workdirbase', "/work")
        self.set('pungi', 'bugurl', 'https://bugzilla.redhat.com')
        self.set('pungi', 'cdsize', '695.0')
        self.set('pungi', 'debuginfo', "True")
        self.set('pungi', 'bootiso', "False")
        self.set('pungi', 'alldeps', "True")
        self.set('pungi', 'isfinal', "False")
        self.set('pungi', 'nohash', "False")
        self.set('pungi', 'full_archlist', "False")
        self.set('pungi', 'multilib', '')
        self.set('pungi', 'lookaside_repos', '')
        self.set('pungi', 'resolve_deps', "True")
        self.set('pungi', 'no_dvd', "False")
Пример #18
0
    def __init__(self):
        SafeConfigParser.__init__(self)
        self.default_config = """
# global options concerning all / multiple modules or theta itself
[global]
debug = False
check_cache = True
        
# minimizer options
[minimizer]
always_mcmc = False
mcmc_iterations = 1000
bootstrap_mcmcpars = 0
# strategy can be 'fast' or 'robust'
strategy = fast
minuit_tolerance_factor = 1
       
[cls_limits]
clb_cutoff = 0.01
create_debuglog = True
        
[model]
use_llvm = False
        
[main]
n_threads = 1
"""
        self.readfp(io.BytesIO(self.default_config))
Пример #19
0
    def __init__(self):
        SafeConfigParser.__init__(self)

        self.add_section('pungi')
        self.add_section('lorax')

        self.set('pungi', 'osdir', 'os')
        self.set('pungi', 'sourcedir', 'source')
        self.set('pungi', 'debugdir', 'debug')
        self.set('pungi', 'isodir', 'iso')
        self.set('pungi', 'relnotefilere', 'GPL README-BURNING-ISOS-en_US.txt ^RPM-GPG')
        self.set('pungi', 'relnotedirre', '')
        self.set('pungi', 'relnotepkgs', 'fedora-release fedora-release-notes')
        self.set('pungi', 'product_path', 'Packages')
        self.set('pungi', 'cachedir', '/var/cache/pungi')
        self.set('pungi', 'compress_type', 'xz')
        self.set('pungi', 'arch', yum.rpmUtils.arch.getBaseArch())
        self.set('pungi', 'name', 'Fedora')
        self.set('pungi', 'iso_basename', 'Fedora')
        self.set('pungi', 'version', time.strftime('%Y%m%d', time.localtime()))
        self.set('pungi', 'flavor', '')
        self.set('pungi', 'destdir', os.getcwd())
        self.set('pungi', 'workdirbase', "/work")
        self.set('pungi', 'bugurl', 'https://bugzilla.redhat.com')
        self.set('pungi', 'cdsize', '695.0')
        self.set('pungi', 'debuginfo', "True")
        self.set('pungi', 'alldeps', "True")
        self.set('pungi', 'isfinal', "False")
        self.set('pungi', 'nohash', "False")
        self.set('pungi', 'full_archlist', "False")
        self.set('pungi', 'multilib', '')
        self.set('pungi', 'lookaside_repos', '')
        self.set('pungi', 'resolve_deps', "True")
        self.set('pungi', 'no_dvd', "False")
        self.set('pungi', 'nomacboot', "False")
Пример #20
0
  def __init__(self, defaults = None, *args, **kwargs):
    
    if not defaults:
      defaults = {}

    SafeConfigParser.__init__(self, *args, **kwargs)
    self.defaults = defaults
Пример #21
0
    def __init__(self, fp, defaults):
        SafeConfigParser.__init__(self)
        self.namespace = {}

        loggingcfg = None
        if fp:
            if fp.read(2) == '#!':
                fp.seek(0)
                exec fp.read() in globals(), self.namespace
                config = self.namespace['__doc__']
            else:
                fp.seek(0)
                config = fp.read()

            # Look for a [[logging]] separator, that introduce a
            # standard logging  section
            cfgs = config.split(LOGGING_SUPER_SECTION)
            if len(cfgs) == 2:
                tailorcfg, loggingcfg = cfgs
            else:
                tailorcfg = cfgs[0]

            self.readfp(StringIO(tailorcfg))

        # Override the defaults with the command line options
        if defaults:
            self._defaults.update(defaults)

        self._setupLogging(loggingcfg and loggingcfg or BASIC_LOGGING_CONFIG)
Пример #22
0
	def __init__(self, server, fd):
		""""""
		SafeConfigParser.__init__(self)
		self.readfp(fd)
		self.server = server
		self.version = self.get(SECTION_MAIN, OPTION_VERSION)
		self.services = self.items(SECTION_UPDATES)
Пример #23
0
 def __init__(self, inifile, defaults=None):
     SafeConfigParser.__init__(self, defaults)
     self.inifile = inifile
     # Make the _sections list an ordered dict, so that the section
     # names occur in order.
     self._sections = OrderedDict()
     self.orderedKeys = {}
Пример #24
0
 def __init__(self, inifile, defaults=None):
     SafeConfigParser.__init__(self, defaults)
     self.inifile = inifile
     # Make the _sections list an ordered dict, so that the section
     # names occur in order.
     self._sections = OrderedDict()
     self.orderedKeys = {}
Пример #25
0
    def __init__(self, files=None, keep_dashes=True):  # pylint: disable=W0231
        """Initialize

        If defaults is True, default option files are read first

        Raises ValueError if defaults is set to True but defaults files
        cannot be found.
        """

        # Regular expression to allow options with no value(For Python v2.6)
        self.OPTCRE = re.compile(  # pylint: disable=C0103
            r'(?P<option>[^:=\s][^:=]*)'
            r'\s*(?:'
            r'(?P<vi>[:=])\s*'
            r'(?P<value>.*))?$')

        self._options_dict = {}

        if PY2:
            SafeConfigParser.__init__(self)
        else:
            SafeConfigParser.__init__(self, strict=False)

        self.default_extension = DEFAULT_EXTENSIONS[os.name]
        self.keep_dashes = keep_dashes

        if not files:
            raise ValueError('files argument should be given')
        if isinstance(files, str):
            self.files = [files]
        else:
            self.files = files

        self._parse_options(list(self.files))
        self._sections = self.get_groups_as_dict()
Пример #26
0
    def __init__(self, files=None, keep_dashes=True):
        """Initialize

        files[in]       The files to parse searching for configuration items.
        keep_dashes[in] If False, dashes in options are replaced with
                        underscores.

        Raises ValueError if defaults is set to True but defaults files
        cannot be found.
        """

        # Regular expression to allow options with no value(For Python v2.6)
        self.OPTCRE = re.compile(  # pylint: disable=C0103
            r'(?P<option>[^:=\s][^:=]*)'
            r'\s*(?:'
            r'(?P<vi>[:=])\s*'
            r'(?P<value>.*))?$')

        self._options_dict = {}

        SafeConfigParser.__init__(self)
        self.default_extension = DEFAULT_EXTENSIONS[os.name]
        self.keep_dashes = keep_dashes

        if not files:
            raise ValueError('files argument should be given')
        if isinstance(files, str):
            self.files = [files]
        else:
            self.files = files

        self._parse_options(list(self.files))
        self._sections = self.get_groups_as_dict()
Пример #27
0
 def __init__(self, config_file=None, defaults=None, dict_type=None):
     if dict_type is not None:
         SafeConfigParser.__init__(self, defaults, dict_type)
     else:
         SafeConfigParser.__init__(self, defaults)
     if config_file is not None:
         self.read(config_file)
Пример #28
0
    def __init__(self, defaults={}, types={}):
        """Constructor.
			If any filenames given tries to parse them
			Input: (string) filename. You can pass pultiple file names
				(dict) defaults: {'section': {'attrib': 'value'}},
				(dict) types: {'section': {'attrib': 'type'}}; types supported are:
					int, str, string, float, bool; default: string
			Output: (Config) class instance
		"""
        # call base class constructors
        SafeConfigParser.__init__(self)
        #UserDict.__init__(self)

        ### IMPORTANT!!! Link self.data to self._sections to provide connectivity between UserDict and SafeConfigParser
        self.data = self._sections
        self._types = types
        self._defaultOptions = defaults
        self._rawData = {}

        for (section, attributes) in defaults.items():
            section = str(section)
            if not self.has_section(section):
                self.add_section(section)
            for (key, value) in attributes.items():
                key = self.optionxform(str(key))
                self.set(section, key, value)
Пример #29
0
    def __init__(self):
        # enforce singleton pattern
        if(not Configuration.__configuration == None):
            raise Configuration.__configuration
        Configuration.__configuration = self

        SafeConfigParser.__init__(self)

        # get a logger
        self.__logger = logging.getLogger("chattest.loadtest.Configuration")
        self.__logger.debug("Created a new Configuration object...")

        # create the default sections
        self.add_section("network")
        self.add_section("users")
        self.add_section("sleep")

        # set the default values
        self.set("network", "host", "localhost")
        self.set("network", "port", "8376")
        self.set("users", "amount", "50")
        self.set("users", "prefix", "loadtest")
        self.set("users", "password", "loadtest")
        self.set("sleep", "start", "5")
        self.set("sleep", "send", "1")
Пример #30
0
 def __init__(self, file_path):
     """"""
     SafeConfigParser.__init__(self)
     try:
         self.read(file_path) #read config file
     except Exception as err:
         logger.info(err)
     self.create_config()
Пример #31
0
 def __init__(self):
     """"""
     SafeConfigParser.__init__(self)
     if not os.path.exists(cons.CONFIG_PATH + HISTORY):
         self.save()
     self.read(cons.CONFIG_PATH + HISTORY)
     self.id = len(self.sections())
     shared.events.connect(cons.EVENT_FILE_COMPLETE, self.add_history)
Пример #32
0
	def __init__(self, path, fd=None):
		""""""
		SafeConfigParser.__init__(self)
		self.path = path
		if fd:
			self.readfp(fd)
		elif os.path.exists(os.path.join(self.path, CONF)):
			self.read(os.path.join(self.path, CONF))
Пример #33
0
 def __init__(self, filename, codec):
     self._comments = {}
     SafeConfigParser.__init__(self)
     self.filename   = filename
     self.codec      = codec
     self.dirty      = False
     self.stamp      = 0xFFFFFFFF
     self.reload()
Пример #34
0
	def __init__(self):
		""""""
		SafeConfigParser.__init__(self)
		if not os.path.exists(cons.CONFIG_PATH + HISTORY):
			self.save()
		self.read(cons.CONFIG_PATH + HISTORY)
		self.id = len(self.sections())
		shared.events.connect(cons.EVENT_FILE_COMPLETE, self.add_history)
Пример #35
0
 def __init__(self, file_path):
     """"""
     SafeConfigParser.__init__(self)
     try:
         self.read(file_path)  #read config file
     except Exception as err:
         logger.info(err)
     self.create_config()
Пример #36
0
 def __init__(self, path, fd=None):
     """"""
     SafeConfigParser.__init__(self)
     self.path = path
     if fd:
         self.readfp(fd)
     elif os.path.exists(os.path.join(self.path, CONF)):
         self.read(os.path.join(self.path, CONF))
Пример #37
0
  def __init__(self):
    SafeConfigParser.__init__(self)

    conf_file = os.path.expanduser('~/.glaciercmd')
    if os.path.isfile(conf_file):
      self.read(conf_file)
    else:
      self._error_messages.append("Could not locate the .glaciercmd configuration file.")
Пример #38
0
 def __init__(self):
     SafeConfigParser.__init__(self)
     # self.config_file = './config.ini'
     config_path = os.path.dirname(__file__)
     self.config_file = os.path.join(config_path, 'config.ini')
     try:
         self.read(self.config_file)
     except Exception:
         traceback.format_exc()
Пример #39
0
	def __init__(s,fn='site.cfg'):
		ConfigParser.__init__( s )
		s.read(fn)
		if not s.has_section('site'):
			s.add_section('site')
		assert s.has_section('tasbot'), 'You need to have a tasbot section in your config file, see site.cfg.example'
		with open(SimpleConfig.tasbot_cfg_filename, 'w') as tasbot_cfg:
			for (name,val) in s.items('tasbot'):
				tasbot_cfg.write( '%s=%s;\n'%(name,val) )
Пример #40
0
 def __init__(self, app=None, defaults=None, dict_type=_default_dict,
              allow_no_value=False):
     SafeConfigParser.__init__(self, defaults=defaults,
                               dict_type=dict_type,
                               allow_no_value=allow_no_value)
     # so the the normalization to lower case does not happen
     self.optionxform = str
     if app is not None:
         self.init_app(app)
Пример #41
0
    def __init__(self, config_file=None):
        if config_file is None:
            config_file = settings.CONFIG_FILE
        logger.debug("levantando la config %s", config_file)

        SafeConfigParser.__init__(self, Configuracion.DEFAULT_CONFIG)
        self.config_file = config_file
        self.section = Configuracion.DEFAULT_SECTION
        self.reload_options()
Пример #42
0
    def __init__(self, *args, **kwargs):
        self.reload()
        SafeConfigParser.__init__(self, *args, **kwargs)

        # The superclass _sections attr takes precedence over the property of
        # the same name defined below. Deleting it exposes that property to hook
        # the config loading mechanism into an attribute used by just about every
        # ConfigParser method.
        self._lazy_sections = self._sections
        del self._sections
Пример #43
0
    def __init__(self, *args, **kwargs):
        self.reload()
        SafeConfigParser.__init__(self, *args, **kwargs)

        # The superclass _sections attr takes precedence over the property of
        # the same name defined below. Deleting it exposes that property to hook
        # the config loading mechanism into an attribute used by just about every
        # ConfigParser method.
        self._lazy_sections = self._sections
        del self._sections
Пример #44
0
 def __init__(self):
     SafeConfigParser.__init__(self)
     filename = os.getenv('KB_API_CONFIG', None)
     if filename is None:
         raise ConfigurationError("KB_API_CONFIG not in environment")
     try:
         with open(filename, 'r') as f:
             self.readfp(f)
     except IOError as e:
         raise ConfigurationError("Could not load configuration file: {0}".format(e))
Пример #45
0
    def __init__(self, configfile):
        SafeConfigParser.__init__(self)
        self.read(
            os.path.join(
                os.path.dirname(__file__),
                'default.cfg'
            ))

        if configfile is not None:
            self.readfp(configfile)
Пример #46
0
    def __init__(self, path=None, fp=None, do_load=True):
        ConfigParser.__init__(self, {"debug": 0})

        if do_load:
            if path:
                self.load_from_path(path)
            elif fp:
                self.readfp(fp)
            else:
                self.read(NeneConfigLocations)
Пример #47
0
    def __init__(self, section=None, strings=False):
        SafeConfigParser.__init__(self)
        self.section = section
        if strings:
            self.read(ConfigHandler.STRINGS_FILENAME)
        else:
            self.read(ConfigHandler.CONFIG_FILENAME)
        if section is not None:

            self.section_vars = dict(self.items(section))
Пример #48
0
 def __init__(s, fn='site.cfg'):
     ConfigParser.__init__(s)
     s.read(fn)
     if not s.has_section('site'):
         s.add_section('site')
     assert s.has_section(
         'tasbot'
     ), 'You need to have a tasbot section in your config file, see site.cfg.example'
     with open(SimpleConfig.tasbot_cfg_filename, 'w') as tasbot_cfg:
         for (name, val) in s.items('tasbot'):
             tasbot_cfg.write('%s=%s;\n' % (name, val))
Пример #49
0
 def __init__(self):
     SafeConfigParser.__init__(self)
     try:
         default_config = pkg_resources.resource_stream(
                 'shaney.sourapples', 'defaults.ini')
     except NameError:
         # the import of pkg_resources must have failed.
         default_config = file(os.path.join(
             os.path.dirname(__file__), 'defaults.ini'))
     self.readfp(default_config)
     self.read(['make_config.ini'])
Пример #50
0
    def __init__(self):
        SafeConfigParser.__init__(self)

        # LOCK Config() and read configuration file
        self._acquireLock()

        # Write Flag
        # Used to prevent writing back to config file if it was just opened for reading
        self.writeFlag = False

        #### Define default config values
        ### [main]
        ## Default DEBUG Value
        self.debug = False

        ### [gui]
        ## Filter checkbox
        self.filter = True

        ### [shows]
        ## My Shows
        self.myShows = []

        ### [display]
        ## Past days to display
        self.numPastDays = 1
        ## Lines
        self.linesFixed = 10
        self.linesMin = 1
        self.linesMax = 10
        self.linesType = "Fixed"  # Values: Fixed / Auto
        ## Format
        self.format = "$show:12:...$-S$season:2$E$episode:2$-$title$"
        ## Theme
        self.theme = Globals().defaultThemeName
        ## Date
        self.dateFormat = "%%d/%%m/%%y"
        ## Date Separator
        self.dateSeparator = "/"
        ## When format
        self.whenFormat = 0

        ### [colors]
        self.myColors = {}
        self.myColors['default'] = "#111111"
        self.myColors['ranges'] = [(-99, -1, "#771111"), (0, 0, "#117711"),
                                   (1, 1, "#111177")]

        ### [misc]
        self.cacheExpiration = 1
        self.browser = "firefox -remote 'openURL($url$,new-tab)'"

        #### Create necessary dir structure
        self._initConfigStorage()
Пример #51
0
 def __init__(self, group_name, app_name, search_path=None,
              filename='app.ini', **kwargs):
     SafeConfigParser.__init__(self, **kwargs)
     self.config = None
     self.group_name = group_name
     self.app_name = app_name
     self.search_path = search_path
     self.filename = filename
     self.loaded_files = []
     self.active_path = []
     self.load()
Пример #52
0
 def __init__(self, files=['/etc/decades/decades.ini', 'decades.ini']):
     SafeConfigParser.__init__(self)
     self.read(files)
     #get the Parameters
     parameters_file = self.get('Config', 'parameters_file')
     with open(parameters_file, 'r') as csvfile:
         self.add_section('Parameters')
         parameters = csv.DictReader(
             csvfile)  #uses first line as fieldnames
         for line in parameters:
             self.set('Parameters', line['ParameterIdentifier'],
                      line['ParameterName'])
Пример #53
0
    def __init__(self):
        SafeConfigParser.__init__(self)
        try:
            f = file('options.cfg')
            self.read('options.cfg')
        except IOError:
            for (k, v) in DEFAULTS.items():
                self.add_section(k)
                for (k2, v2) in v.items():
                    self.set(k, str(k2), str(v2))

            f = file('options.cfg', 'w')
            self.write(f)
Пример #54
0
    def __init__(self, filename="wxfalsecolor.cfg", logger=None):
        self._log = logger if logger else DummyLogger()
        self.filename = filename
        SafeConfigParser.__init__(self)
        self.set_defaults(BUILT_IN_CONFIG)

        ## read config file if it exists
        configfile = self.get_filepath()
        if os.path.isfile(configfile):
            self._log.info("reading config file '%s'" % configfile)
            self.read(configfile)

        ## set this after defaults and existing file have been loaded
        self._changed = False
Пример #55
0
 def __init__(self, configfile=None):
     SafeConfigParser.__init__(self)
     configfiles = []
     # Add the filename for the config file in the modules
     # directory
     self.opengrid_libdir = os.path.dirname(
         os.path.abspath(inspect.getfile(inspect.currentframe())))
     configfiles.append(os.path.join(self.opengrid_libdir, 'opengrid.cfg'))
     # Add the filename for the config file in the 'current' directory
     configfiles.append('opengrid.cfg')
     # Add the filename for the config file passed in
     if configfile:
         configfiles.append(configfile)
     self.read(configfiles)
Пример #56
0
    def __init__(self, path, **kwargs):
        SafeConfigParser.__init__(self, **kwargs)

        if isinstance(path, (list, tuple)):
            for p in path:
                self.check_file_existence(p)
        else:
            self.check_file_existence(path)

        self.path = path
        self.kwargs = kwargs

        logger.debug('Reading config(s) at %r. Given kwargs are:\n\n%s\n',
                     self.path, pformat(self.kwargs))