123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202 |
- """
- Configuration Module.
- This reads the configuration file and conveniently makes the settings available to KCG
- """
- import ConfigParser
- import ast
- import os
- import sys
- import logging
- class NoValueException(Exception):
- """
- Simple Exception that gets thrown when no Value was given in the configuration file
- """
- pass
- class MisconfigurationError(Exception):
- """
- Simple Exception to indicate that a misconfiguration was found.
- """
- pass
- def leval(string):
- """
- Wrapper arount ast.literal_eval that throws NoValueException if the value was empty
- :param string:
- :return:
- """
- if string == "":
- raise NoValueException("No value given for option")
- else:
- return ast.literal_eval(string)
- class ConfSection(object):
- """
- Class to handle a section in the configuration.
- """
- def __init__(self, section, settings, config_object, default_config_object=None, log_level=logging.ERROR):
- self._section = section
- self._settings = settings
- self._conf_obj = config_object
- self._def_conf_obj = default_config_object
- self._arg_dict = {}
- self._log_level = log_level
- def feed_arguments(self, arg_dict):
- """
- Feed this section with commandline arguments for this section. The given arguments will
- override the ones in configuration files.
- :param arg_dict: the dictionary for all sections
- :return:
- """
- if self._section in arg_dict:
- self._arg_dict = arg_dict[self._section]
- else:
- self._arg_dict = {}
- def read(self):
- """
- Read and evaluate configuration settings.
- :return:
- """
- error = False
- for conf in self._settings:
- if conf in self._arg_dict:
- try:
- globals()[conf] = leval(self._arg_dict[conf])
- continue
- except Exception:
- if self._log_level <= logging.ERROR:
- print "Error in parsing commandline configuration using configuration in config file."
- if self._conf_obj.has_option(self._section, conf):
- try:
- globals()[conf] = leval(self._conf_obj.get(self._section, conf))
- except NoValueException:
- error = True
- elif self._def_conf_obj is not None:
- if self._log_level <= logging.DEBUG:
- print "Using default configuration value for " + conf
- globals()[conf] = leval(self._def_conf_obj.get(self._section, conf))
- else:
- error = True
- return not error
- class Configuration(object):
- """
- Class to handle configuration
- """
- def __init__(self, args=None, log_level=logging.INFO):
- self._args = args
- self._parsed_args = {}
- self.error = False
- self._log_level = log_level
- globals()['config_object'] = self
- globals()['log_level'] = log_level
- if args:
- self.parse_command_line()
- def parse_command_line(self):
- """
- Parses the command line configuration arguments
- :return:
- """
- if ';' in self._args:
- self._args = self._args.split(';')
- else:
- self._args = [self._args]
- for setting in self._args:
- if setting == '':
- continue
- try:
- sec, set = setting.strip().split('->')
- sets, setv = set.split('=')
- section = self._parsed_args.setdefault(sec, {})
- section[sets.strip()] = setv.strip()
- except:
- print "Format of commandline configuration is wrong. Using config file version"
- def read(self):
- """
- This function reads the configuration file and the default config fille (in case the
- user config file does not contain all values) and adds them as parameters to this module
- :return:
- """
- config = ConfigParser.ConfigParser()
- config.optionxform = str
- config.read(os.path.expanduser("~")+"/.kcg/config.cfg")
- defaultConfig = ConfigParser.ConfigParser()
- defaultConfig.optionxform = str
- defaultConfig.read(os.path.join(os.path.dirname(__file__), "config.cfg"))
- Machine_conf = ["bunches_per_turn", "save_header", "tRev"]
- Ui_conf = ["language", "default_save_location", "default_subdirectory_name", "force_ask", "show_advanced_control", "integrate_single_read"]
- Logging_conf = ["epics_test_pv", "epics_base_path", "epics_log_entry_pvs", "default_log_entries"]
- Misc_conf = ['newPlotLiveIcon', 'newPlotDataIcon', 'timingIcon', 'singleReadIcon',
- 'acquireSettingsIcon', 'startIcon', 'stopIcon', 'logIcon', 'logCommentIcon', 'guiIcon', 'style',
- 'board_detection_method', 'device_list', 'device_names',
- 'num_dummy_boards']
- try:
- machine_c = ConfSection('Machine', Machine_conf, config, log_level=self._log_level)
- machine_c.feed_arguments(self._parsed_args)
- self.error = True if not machine_c.read() else self.error
- ui_c = ConfSection('Ui', Ui_conf, config, defaultConfig, self._log_level)
- ui_c.feed_arguments(self._parsed_args)
- self.error = True if not ui_c.read() else self.error
- logging_c = ConfSection('Logging', Logging_conf, config, defaultConfig, self._log_level)
- logging_c.feed_arguments(self._parsed_args)
- self.error = True if not logging_c.read() else self.error
- misc_c = ConfSection('Misc', Misc_conf, config, defaultConfig, self._log_level)
- misc_c.feed_arguments(self._parsed_args)
- self.error = True if not misc_c.read() else self.error
- # if config.has_section('Misc'):
- # for conf, val in config.items("Misc"):
- # globals()[conf] = leval(val)
- # for conf, val in defaultConfig.items("Misc"):
- # if not conf in globals().keys():
- # globals()[conf] = leval(val)
- except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e:
- self.error = True
- print "There was an error parsing configuration: " + str(e)
- def setup(self):
- """
- Check for the user config file and if not exists calls doSetup
- :return:
- """
- if not os.path.isfile(os.path.expanduser("~")+"/.kcg/config.cfg"):
- self.doSetup()
- else:
- self.read()
- def doSetup(self, rerun=False, parent=None):
- """
- Shows the initial config dialog
- :return:
- """
- from widgets.initialconfig import ConfigSetup
- from PyQt4 import QtGui, QtCore
- if not rerun:
- setupConfigApp = QtGui.QApplication([])
- self.setupConfig = ConfigSetup()
- self.setupConfig.show()
- setupConfigApp.exec_()
- if not self.setupConfig.result:
- sys.exit(122)
- else:
- self.setupConfig = ConfigSetup(restart=True)
- self.setupConfig.setWindowModality(QtCore.Qt.ApplicationModal)
- self.setupConfig.show()
- self.error = False
- self.read()
|