class Playlist(object): def __init__(self, location): dir = os.path.expanduser(os.path.dirname(location)) if not os.path.exists(dir): os.makedirs(dir) self._config = ConfigParser() self._config.optionxform = str self._file = os.path.expanduser(location) if os.path.exists(self._file): self._config.read(self._file) else: self._config.add_section('Playlist') self.save() def save(self): self._config.write(open(self._file, 'wb')) def append(self, item): self._config.set('Playlist', *item) self.save() def remove(self, option): self._config.remove_option('Playlist', option) self.save() def __getitem__(self, item): return self._config.items('Playlist')[item] def __iter__(self): return iter(self._config.items('Playlist'))
def write_last_synced(self, _value, _job, _new, _smb_connection=None): """ Write _value to the last_synced property of the destination status file :param _value: The value to write :param _job: A SyncJob instance :param _new: If there isn't already a history-section :param _smb_connection: An SMB connection. :return: """ if _new is None: if _smb_connection is not None: _file_obj = read_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt')) else: try: _file_obj = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r") except IOError: pass else: _file_obj = StringIO.StringIO() _cfg = ConfigParser() _cfg.readfp(_file_obj) if _new is not None: _cfg.add_section("history") _cfg.set("history", "last_synced", _value) _cfg.write(_file_obj) if _smb_connection is not None: write_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt'), _file_obj) else: try: _file = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r") except IOError: pass
def startSetup(): config = ConfigParser() moduleList = listdir("modules") config.add_section("global") value = raw_input("Enter the JSON root folder to write the json files too : ") if value[-1] != "/": value += "/" config.set("global", "jsonRoot", value) modulesConfig = [] for module in moduleList: if module == "__init__.py" or module[-3:] != ".py": continue loadedModule = __import__("modules." + module[:-3], fromlist=["*"]) moduleConfig = loadedModule.startConfig(config) modulesConfig.append(moduleConfig) modulesConfigDict = {} modulesConfigDict["moduleList"] = modulesConfig configString = json.dumps(modulesConfigDict) modulesFile = open(config.get("global", "jsonRoot") + "modules.json", "w") modulesFile.write(configString) modulesFile.close() configFile = open("server.cfg", "w") config.write(configFile) configFile.close()
def edit_account_config(self, config, **kwargs): """ Launches an editor to edit a user or group configuration """ account_type = self._config_account_type(config) if not kwargs: # interactive mode # save config to file temp_fd, temp_filename = mkstemp(suffix=".ini", text=True) try: temp_file = os.fdopen(temp_fd, "w") config.write(temp_file) temp_file.close() # open config in editor editor = os.environ.get('EDITOR', 'vi') subprocess.call([editor, temp_filename]) # fetch config from file new_config = ConfigParser() new_config.read(temp_filename) finally: os.remove(temp_filename) else: new_config = config for key in kwargs: new_config.set(account_type, key, kwargs[key]) # Sanity check resulting config if account_type == "user": User("foo", new_config) elif account_type == "group": Group("foo", new_config) return new_config
class UserConfig: def __init__(self, filename=default_user_config_file): self.parser = ConfigParser() self.parser.read(filename) self.filename = filename if not isfile(self.filename): self.parser.add_section('diaspora') self.set_activated(False) self.__save() else: self.parser.read(self.filename) if not self.parser.has_section('diaspora'): self.parser.add_section('diaspora') def is_installed(self): return self.parser.getboolean('diaspora', 'activated') def set_activated(self, value): self.parser.set('diaspora', 'activated', str(value)) self.__save() def __save(self): with open(self.filename, 'wb') as f: self.parser.write(f)
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
def auth_springpad_client(config_file=None): """ Auth the application to make to be allowed to access to user's springpad account. If not a valid config file is provided it will prompt the user to visit an url in order to allow the application to access to its account and it will store authentication details in `config_file`. args: config_file: the configuration file path to be used. If it is not provided, '~/.springpad' will be used instead. returns: SpringpadClient instance to interact with the authenticated account. """ config_file = config_file or os.path.expanduser("~/.springpad") config = ConfigParser() config.read([config_file]) token = config.get("access", "token") if config.has_option("access", "token") else None if token: token = oauth.OAuthToken.from_string(token) client = SpringpadClient(SPRINGPAD_CONSUMER_KEY, SPRINGPAD_CONSUMER_PRIVATE, token) if not client.access_token: req_token = client.get_request_token() print "Please grant access to your springpad account in the following url:\n" print "http://springpad.com/api/oauth-authorize?{0}\n".format(req_token) print "Once authorized, press intro to continue:", raw_input() client.access_token = client.get_access_token(req_token) config.add_section("access") config.set("access", "token", str(client.access_token)) with open(os.path.expanduser(config_file), "w") as cf: config.write(cf) return client
def write_ini_config_file(self, command, data, client): """\ Write the new command configuration in the plugin configuration file """ try: # read the config file config = ConfigParser() config.read(command.plugin.config.fileName) # if there is no commands section if not config.has_section('commands'): raise NoSectionError('could not find <commands> section in ' 'plugin <%s> config file' % data['plugin_name']) # remove the old entry found = False for temp in config.options('commands'): search = temp.split('-')[0] if search == command.command: config.remove_option('commands', temp) found = True # set the new command option value config.set('commands', data['command_name'], data['command_level']) self.debug('%s command <%s> in plugin <%s> config file' % ('updated' if found else 'created new entry for', command.command, data['plugin_name'])) # write the updated configuration file with open(command.plugin.config.fileName, 'wb') as configfile: config.write(configfile) except (IOError, NoSectionError), e: self.warning('could not change plugin <%s> config file: %s' % (data['plugin_name'], e)) client.message('^7could not change plugin ^1%s ^7config file' % data['plugin_name'])
def install_mercurial_hook(): """ Installs the mercurial precommit hook by adding a hook to the hgrc file in the .hg directory of the repository. """ repo_dir = get_repo_dir() config_file = os.path.join(repo_dir, '.hg', 'hgrc') config_parser = ConfigParser() config_parser.read(config_file) precommit_abs_file = os.path.join(repo_dir, 'scripts', 'codestyleprecommit.py') section = 'hooks' key = 'pretxncommit.precommit' value = 'python:%s:mercurial_hook' % precommit_abs_file if not config_parser.has_section(section): config_parser.add_section(section) config_parser.set(section, key, value) with open(config_file, 'w') as config: config_parser.write(config)
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)
def _hg_hook(self): # In hg, hooks can be set in config hgrc = "%s/.hg/hgrc" % self.vcs_path parser = ConfigParser() files = parser.read(hgrc) if not files: conf.log.warning("Failed to find mercurial config: {0}".format(hgrc)) return False try: # Set hook path = os.path.join(conf.version_control_hooks_dir, "hg-incoming") if 'hooks' not in parser.sections(): parser.add_section('hooks') parser.set('hooks', 'incoming', path) # Write hook in config with open(hgrc, "w") as hgrc_file: parser.write(hgrc_file) except Exception: conf.log.exception("Failed to hook with mercurial repository") return False return True
def set_config(self, config): cp = ConfigParser() cp.add_section(self.DEFAULT_INI_SECTION) for k, v in config.items(): cp.set(self.DEFAULT_INI_SECTION, k, v) with open(self.ini_file_name, "w") as f: cp.write(f)
def set(self, section, option, value): """Set an option value. Knows how to set options properly marked as secure.""" if self.is_secure_option(section, option): self.set_secure(section, option, value) else: ConfigParser.set(self, section, option, value)
def update_config(repo_file, enabled=True): """Enables or disables all sections in Yum config files :param repo_file: Config file, which should be processed :type repo_file: str :param enabled: Whether to enable or disable :type enabled: bool """ if os.path.isfile(repo_file): cfg = ConfigParser() cfg.read([repo_file]) save_changes = False for section in cfg.sections(): if cfg.has_option(section, 'enabled'): save_changes = True if enabled: cfg.set(section, 'enabled', 1) else: cfg.set(section, 'enabled', 0) if save_changes: fd = open(repo_file, 'rwa+') cfg.write(fd) fd.close() else: pytest.fail(msg="%s was not found!" % repo_file)
def save_action_to_file(action, f): parser = ConfigParser() parser.add_section('action') for action_k, action_v in action.items(): parser.set('action', action_k, action_v) parser.write(f) f.seek(0)
class RepoConfig(object): ''' This class provides an abstraction around repository configuration files ''' def __init__(self, path): ''' :param path: Plumbum path to the repository ''' self._config = ConfigParser() self._path = path / '.hg' / 'hgrc' if self._path.exists(): self._config.readfp(self._path.open()) else: self._config.add_section('paths') def AddRemote(self, name, destination): ''' Adds a remote to the config, or overwrites if it already exists :param name: The name of the remote :param destination: The destination path of the remote ''' self._config.set('paths', name, destination) self._config.write(self._path.open('w')) @property def remotes(self): ''' Property to get a dictionary of remotes ''' return dict(self._config.items('paths'))
def create_project(harvest_version, project_name): package_name = project_dir = project_name if os.path.exists(project_dir): print(red('Error: project directory already exists')) sys.exit(1) if template: archive_url = '{0}/archive/HEAD.zip'.format(template) archive = 'custom-template.zip' else: archive_url = config.TEMPLATE_ARCHIVE_URL.format(harvest_version) archive = config.TEMPLATE_ARCHIVE.format(harvest_version) download = True if os.path.exists(archive): download = prompt('{0} archive already exists. Redownload? '.format(archive), default='n', validate=r'^[YyNn]$').lower() if download == 'n': download = False else: os.remove(archive) if download: print(green('- Downloading Harvest @ {0}'.format(harvest_version))) local('wget -O "{0}" "{1}"'.format(archive, archive_url), shell='/bin/bash') # Expected directory name of template template_dir = zipfile.ZipFile(archive).namelist()[0].rstrip('/') # Remove existing unarchived directory if os.path.exists(template_dir): local('rm -rf {0}'.format(template_dir), shell='/bin/bash') with hide(*hidden_output): local('unzip {0}'.format(archive), shell='/bin/bash') local('rm -rf {0}'.format(archive), shell='/bin/bash') # Rename template to project name local('mv {0} {1}'.format(template_dir, project_dir), shell='/bin/bash') # Get the template's main package name cparser = ConfigParser() cparser.read(os.path.join(project_dir, config.HARVESTRC_PATH)) old_package_name = cparser.get('harvest', 'package') # Replace old package name with new one find_replace(project_dir, old_package_name, package_name) # Rename package to new name with lcd(project_dir): local('mv {0} {1}'.format(old_package_name, package_name), shell='/bin/bash') # Set the new package name and version cparser.set('harvest', 'package', package_name) cparser.set('harvest', 'version', template_dir.split('-')[-1]) with lcd(project_dir): with open(config.HARVESTRC_PATH, 'w') as rc: cparser.write(rc)
class RedirectConfig: def __init__(self, filename): self.parser = ConfigParser() self.parser.read(filename) self.filename = filename self.logger = logger.get_logger('insider.RedirectConfig') def update(self, domain, api_url): self.logger.info('settig domain={0}, api_url={1}'.format(domain, api_url)) if not self.parser.has_section('redirect'): self.parser.add_section('redirect') self.parser.set('redirect', 'domain', domain) self.parser.set('redirect', 'api_url', api_url) self._save() def get_domain(self): return self.parser.get('redirect', 'domain') def get_api_url(self): return self.parser.get('redirect', 'api_url') def _save(self): self.logger.info('saving config={0}'.format(self.filename)) with open(self.filename, 'wb') as file: self.parser.write(file)
class InsiderConfig: def __init__(self, filename): self.parser = ConfigParser() self.parser.read(filename) self.filename = filename self.redirect_config = RedirectConfig(join(dirname(filename), 'redirect.cfg')) self.logger = logger.get_logger('insider.InsiderConfig') def _save(self): self.logger.info('saving config={0}'.format(self.filename)) with open(self.filename, 'wb') as file: self.parser.write(file) def update(self, domain, api_url): self.redirect_config.update(domain, api_url) def get_redirect_api_url(self): return self.redirect_config.get_api_url() def get_redirect_main_domain(self): return self.redirect_config.get_domain() def get_cron_period_mins(self): return self.parser.getint('cron', 'period_mins') def is_upnpc_mock(self): return self.parser.getboolean('upnpc', 'mock') def set_upnpc_mock(self, enable): if not self.parser.has_section('upnpc'): self.parser.add_section('upnpc') self.parser.set('upnpc', 'mock', enable) self._save()
def load_configparser(config_file=None): cp = CP() if config_file is not None: config_file = resolve_file(config_file) if not os.path.isfile(config_file): es = "Could not find configuration file [%s]" raise ValueError(es % (config_file)) else: possible_config_files = ['zdstackrc', 'zdstack.ini', '~/.zdstackrc', '~/.zdstack.ini', '~/.zdstack/zdstackrc', '~/.zdstack/zdstack.ini', '/etc/zdstackrc', '/etc/zdstack.ini', '/etc/zdstack/zdstackrc' '/etc/zdstack/zdstack.ini'] possible_config_files = \ [resolve_file(x) for x in possible_config_files] if not [y for y in possible_config_files if os.path.isfile(y)]: raise ValueError("Could not find a valid configuration file") config_file = possible_config_files[0] config_fobj = StringIO(read_file(config_file)) regexp = r'^\[(.*)\]%' sections = [] for line in config_fobj.getvalue().splitlines(): if re.match(regexp, line) and line in sections: es = "Duplicate section found in config: [%s]" raise ValueError(es % (line)) config_fobj.seek(0) cp.readfp(config_fobj) cp.filename = config_file for section in cp.sections(): cp.set(section, 'name', section) return cp
def configure_manager(manager_config_path, manager_config): '''Sets config defaults and creates the config file''' _, temp_config = tempfile.mkstemp() config = ConfigParser() config.add_section('Credentials') config.set('Credentials', 'subscription_id', manager_config['subscription_id']) config.set('Credentials', 'tenant_id', manager_config['tenant_id']) config.set('Credentials', 'client_id', manager_config['client_id']) config.set('Credentials', 'client_secret', manager_config['client_secret']) config.add_section('Azure') config.set('Azure', 'location', manager_config['location']) with open(temp_config, 'w') as temp_config_file: config.write(temp_config_file) fabric.api.sudo('mkdir -p {0}'. format(os.path.dirname(manager_config_path))) fabric.api.put(temp_config, manager_config_path, use_sudo=True)
def run_gui(input_start_page, end_page, strict): """ Batch cleans the pages in text/clean.""" config = ConfigParser() config.read('book.cnf') if strict and \ config.has_option('process', 'last_strict_page'): hold_page = config.getint('process', 'last_strict_page') elif not strict and \ config.has_option('process', 'last_checked_page'): hold_page = config.getint('process', 'last_checked_page') else: hold_page = input_start_page print hold_page if input_start_page == 0: start_page = hold_page else: start_page = input_start_page lang = get_lang() lm = line_manager.LineManager( spell_checker.AspellSpellChecker(lang, './dict.{}.pws'.format(lang)), start_page, end_page ) lm.load('text/clean') app = gui.main(lm, strict) lm.write_pages('text/clean', False) if strict and int(app.last_page) >= hold_page: config.set('process', 'last_strict_page', app.last_page) elif not strict and int(app.last_page) >= hold_page: config.set('process', 'last_checked_page', app.last_page) with open('book.cnf', 'wb') as f: config.write(f)
def hour_set(arg, hour): cp = ConfigParser() cp.read("conf.txt") cp.set("pills_must_be_taken", "hour", hour) hd = open("conf.txt", "w") cp.write(hd) hd.close()
def addRegra(self, ipORrede, nome, banda_liberada, banda_down, prio, delimitado, isolado): #system("tc qdisc del dev %s root"%self.device) arquivo = ConfigParser() arquivo.read( '/var/lib/netcontrol/plugins/limite_banda/etc/config_server' ) if not arquivo.has_section("contador_regras"): arquivo.add_section("contador_regras") arquivo.set("contador_regras","contador",1) arquivo.write( open('/var/lib/netcontrol/plugins/limite_banda/etc/config_server','w') ) cont = "1" else: cont = int(arquivo.get("contador_regras", "contador")) + 1 arquivo.set("contador_regras","contador", cont) arquivo.write( open('/var/lib/netcontrol/plugins/limite_banda/etc/config_server','w') ) cont = str(cont) cont = "000%s"%(cont) ip = ipORrede.replace('.','_').replace('/','_') user = nome.replace(' ','_') nome = "cbq-%s.%s%s-in"%(cont[-4:],ip,user) regra = "DEVICE=%s,%s,%s\n" \ "RATE=%sKbit\n" \ "WEIGHT=%sKbit\n" \ "PRIO=%s\n" \ "RULE=%s\n" \ "BOUNDED=%s\n" \ "ISOLATED=%s"%(self.device, self.banda_total, self.banda_total_down, banda_liberada, banda_down, prio, ipORrede, delimitado, isolado) open('%s%s'%(self.etc,nome),'w').write(regra)
def mail_set(arg, email): cp = ConfigParser() cp.read("conf.txt") cp.set("parents", "mail", email) hd = open("conf.txt", "w") cp.write(hd) hd.close()
def set_config_to_path(configPath, section, option, value): read = False #check if config file exists if ( os.path.isfile(configPath)): configPath = os.path.realpath(configPath); config = ConfigParser(); #try to read the value from ini file try: config.read(configPath) if config.has_section(section) : #Update the new values config.set(section, option, value) read = True except: #read failed due currupted ini file that can happen due to suddent power of during update print "except" if( read == False): #file not exist and needs to be creatred config = ConfigParser(); config.add_section(section) config.set(section, option, value) read = True fo=open(configPath, "w+") config.write(fo) # Write update config return read
def start_config(config_file_name): config = ConfigParser() config.add_section("global") value = raw_input("Enter the JSON root folder to write the json files too : ") if len(value) == 0: value = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/www/JSON' elif value[-1] != "/": value += "/" config.set("global", "json_root", value) modules_config = [] module_list = os.listdir(os.path.dirname(os.path.abspath(__file__))) for module in module_list: if module == "__init__.py" or module[-3:] != ".py" or module[:4] == 'main': continue loaded_module = __import__("pygamescanner." + module[:-3], fromlist=["*"]) module_config = loaded_module.start_config(config) modules_config.append(module_config) modules_config_dict = dict() modules_config_dict["module_list"] = modules_config config_string = json.dumps(modules_config_dict) modules_file = open(config.get("global", "json_root") + "modules.json", "w") modules_file.write(config_string) modules_file.close() config_file = open(config_file_name, "w") config.write(config_file) config_file.close()
def minutes_set(arg, mins): cp = ConfigParser() cp.read("conf.txt") cp.set("pills_must_be_taken", "minutes", mins) hd = open("conf.txt", "w") cp.write(hd) hd.close()
def update_configuration(section, parameter, new_value): config = ConfigParser() config.read(configuration_file) config.set(section, parameter, new_value) log("[%s] The %s variable of %s has been changed to %s" %(datetime.datetime.now(), parameter, section, new_value)) with open(configuration_file, 'w') as configfile: config.write(configfile)
class SetupConfig(object): """Wrapper around the setup.cfg file if available. Mostly, this is here to cleanup setup.cfg from these settings: [egg_info] tag_build = dev tag_svn_revision = true """ config_filename = SETUP_CONFIG_FILE def __init__(self): """Grab the configuration (overridable for test purposes)""" # If there is a setup.cfg in the package, parse it if not os.path.exists(self.config_filename): self.config = None return self.config = ConfigParser() self.config.read(self.config_filename) def has_bad_commands(self): if self.config is None: return False if not self.config.has_section('egg_info'): # bail out early as the main section is not there return False bad = False # Check 1. if self.config.has_option('egg_info', 'tag_build'): # Might still be empty. value = self.config.get('egg_info', 'tag_build') if value: logger.warn("%s has [egg_info] tag_build set to %r", self.config_filename, value) bad = True # Check 2. if self.config.has_option('egg_info', 'tag_svn_revision'): if self.config.getboolean('egg_info', 'tag_svn_revision'): value = self.config.get('egg_info', 'tag_svn_revision') logger.warn("%s has [egg_info] tag_svn_revision set to %r", self.config_filename, value) bad = True return bad def fix_config(self): if not self.has_bad_commands(): logger.warn("Cannot fix already fine %s.", self.config_filename) return if self.config.has_option('egg_info', 'tag_build'): self.config.set('egg_info', 'tag_build', '') if self.config.has_option('egg_info', 'tag_svn_revision'): self.config.set('egg_info', 'tag_svn_revision', 'false') new_setup = open(self.config_filename, 'wb') try: self.config.write(new_setup) finally: new_setup.close() logger.info("New setup.cfg contents:") print ''.join(open(self.config_filename).readlines())
def save_scenario(self, scenario_file_path=None): """Save current scenario to a text file. You can use the saved scenario with the batch runner. :param scenario_file_path: A path to the scenario file. :type scenario_file_path: str """ # Validate Input warning_title = self.tr('InaSAFE Save Scenario Warning') is_valid, warning_message = self.validate_input() if not is_valid: # noinspection PyCallByClass,PyTypeChecker,PyArgumentList QtGui.QMessageBox.warning(self, warning_title, warning_message) return # Make extent to look like: # 109.829170982, -8.13333290561, 111.005344795, -7.49226294379 # Added in 2.2 to support user defined analysis extents if self.dock.extent.user_extent is not None \ and self.dock.extent.user_extent_crs is not None: extent = extent_to_array(self.dock.extent.user_extent, self.dock.extent.user_extent_crs) else: extent = viewport_geo_array(self.iface.mapCanvas()) extent_string = ', '.join(('%f' % x) for x in extent) exposure_path = self.exposure_layer.publicSource() hazard_path = self.hazard_layer.publicSource() title = self.keyword_io.read_keywords(self.hazard_layer, 'title') title = self.tr(title) default_filename = title.replace(' ', '_').replace('(', '').replace(')', '') # Popup a dialog to request the filename if scenario_file_path = None dialog_title = self.tr('Save Scenario') if scenario_file_path is None: # noinspection PyCallByClass,PyTypeChecker scenario_file_path = QFileDialog.getSaveFileName( self, dialog_title, os.path.join(self.output_directory, default_filename + '.txt'), "Text files (*.txt)") if scenario_file_path is None or scenario_file_path == '': return self.output_directory = os.path.dirname(scenario_file_path) # Get relative path for each layer relative_exposure_path = self.relative_path(scenario_file_path, exposure_path) relative_hazard_path = self.relative_path(scenario_file_path, hazard_path) # Write to file parser = ConfigParser() parser.add_section(title) parser.set(title, 'exposure', relative_exposure_path) parser.set(title, 'hazard', relative_hazard_path) parser.set(title, 'function', self.function_id) parser.set(title, 'extent', extent_string) if self.dock.extent.user_extent_crs is None: parser.set(title, 'extent_crs', 'EPSG:4326') else: parser.set(title, 'extent_crs', self.dock.extent.user_extent_crs.authid()) if self.aggregation_layer is not None: aggregation_path = self.aggregation_layer.publicSource() relative_aggregation_path = self.relative_path( scenario_file_path, aggregation_path) parser.set(title, 'aggregation', relative_aggregation_path) try: parser.write(open(scenario_file_path, 'a')) except IOError: # noinspection PyTypeChecker,PyCallByClass,PyArgumentList QtGui.QMessageBox.warning( self, self.tr('InaSAFE'), self.tr('Failed to save scenario to ' + scenario_file_path)) # Save State self.save_state()
class ConfBuilder(object): ''' This class manages the configuration files ''' def __init__(self): # excludes from the generic variables parsing the ones that have a # certain logic warpped around them self.exclude_from_generic = [ 'DD_API_KEY', 'DD_API_KEY_FILE', 'DD_HOME', 'DD_START_AGENT', 'DD_LOGS_STDOUT' ] dd_agent_root = '/etc/dd-agent' dd_home = getenv('DD_HOME') if dd_home is not None: dd_agent_root = '{}/agent'.format(dd_home) self.datadog_conf_file = '{}/datadog.conf'.format(dd_agent_root) # This will store the config parser object that is used in the different functions self.config = None def load_config(self, config_file): ''' Loads a config file using ConfigParser ''' self.config = ConfigParser() # import existing config from file with open(config_file, 'rb') as cfd: self.config.readfp(cfd) def save_config(self, config_file): ''' Saves a ConfigParser object (self.config) to the given file ''' if self.config is None: logging.error( 'config object needs to be created before saving anything') exit(1) with open(config_file, 'wb') as cfd: self.config.write(cfd) def build_datadog_conf(self): ''' Builds the datadog.conf based on the environment variables ''' self.load_config(self.datadog_conf_file) ##### Core config ##### self.set_api_key() self.set_from_env_mapping('DD_HOSTNAME', 'hostname') self.set_from_env_mapping('EC2_TAGS', 'collect_ec2_tags') # The TAGS env variable superseeds DD_TAGS self.set_from_env_mapping('DD_TAGS', 'tags') self.set_from_env_mapping('TAGS', 'tags') self.set_from_env_mapping('DD_COLLECT_LABELS_AS_TAGS', 'docker_labels_as_tags') # The LOG_LEVEL env variable superseeds DD_LOG_LEVEL self.set_from_env_mapping('DD_LOG_LEVEL', 'log_level') self.set_from_env_mapping('LOG_LEVEL', 'log_level') self.set_from_env_mapping('NON_LOCAL_TRAFFIC', 'non_local_traffic') self.set_from_env_mapping('DD_URL', 'dd_url') self.set_from_env_mapping('STATSD_METRIC_NAMESPACE', 'statsd_metric_namespace') self.set_from_env_mapping('USE_DOGSTATSD', 'use_dogstatsd') ##### Proxy config ##### self.set_from_env_mapping('PROXY_HOST', 'proxy_host') self.set_from_env_mapping('PROXY_PORT', 'proxy_port') self.set_from_env_mapping('PROXY_USER', 'proxy_user') self.set_from_env_mapping('PROXY_PASSWORD', 'proxy_password') ##### Service discovery ##### self.set_from_env_mapping('SD_BACKEND', 'service_discovery_backend') self.set_sd_backend_host() self.set_from_env_mapping('SD_BACKEND_PORT', 'sd_backend_port') self.set_from_env_mapping('SD_TEMPLATE_DIR', 'sd_template_dir') self.set_from_env_mapping('SD_CONSUL_TOKEN', 'consul_token') self.set_from_env_mapping('SD_BACKEND_USER', 'sd_backend_username') self.set_from_env_mapping('SD_BACKEND_PASSWORD', 'sd_backend_password') # Magic trick to automatically add properties not yet define in the doc self.set_generics('DD_CONF_') self.save_config(self.datadog_conf_file) def set_api_key(self): ''' Used for building datadog.conf Gets the API key from the environment or the key file and sets it in the configuration ''' api_key = getenv('DD_API_KEY', getenv('API_KEY', '')) keyfile = getenv('DD_API_KEY_FILE') if keyfile is not None: try: with open(keyfile, 'r') as kfile: api_key = kfile.read() except IOError: logging.warning( 'Unable to read the content of they key file specified in DD_API_KEY_FILE' ) if len(api_key) <= 0: logging.error( 'You must set API_KEY environment variable or include a DD_API_KEY_FILE to run the Datadog Agent container' ) exit(1) self.set_property('api_key', api_key) def set_from_env_mapping(self, env_var_name, property_name, section='Main', action=None): ''' Sets a property using the corresponding environment variable if it exists It also returns the value in case you want to play with it If action is specified to 'store_true', whatever the content of the env variable is (if exists), the value of the property will be true ''' _val = getenv(env_var_name) if _val is not None: if action == 'store_true': _val = 'true' self.set_property(property_name, _val, section) return _val return None def set_sd_backend_host(self): ''' Used for building datadog.conf Sets sd_config_backend and sd_backend_host depending on the environment ''' _config_backend = getenv('SD_CONFIG_BACKEND') if _config_backend is not None: self.set_property('sd_config_backend', _config_backend) _backend_host = getenv('SD_BACKEND_HOST') if _backend_host is not None: self.set_property('sd_backend_host', _backend_host) else: _timeout = getdefaulttimeout() try: setdefaulttimeout(1) _ec2_ip = urlopen( 'http://169.254.169.254/latest/meta-data/local-ipv4') self.set_property('sd_backend_host', _ec2_ip.read()) except (URLError, HTTPError): pass # silent fail on purpose setdefaulttimeout(_timeout) def set_generics(self, prefix='DD_CONF_'): ''' Looks for environment variables starting by the given prefix and consider that the rest of the variable name is the name of the property to set ''' for dd_var in environ: if dd_var.startswith(prefix) and dd_var.upper( ) not in self.exclude_from_generic: if len(dd_var) > 0: self.set_property(dd_var[len(prefix):].lower(), environ[dd_var]) def set_property(self, property_name, property_value, section='Main'): ''' Sets the given property to the given value in the configuration ''' if self.config is None: logging.error( 'config object needs to be created before setting properties') exit(1) self.config.set(section, property_name, property_value)
class Connector(): '''Модуль для обеспечения взаимодействия модуля-обработчика OpenVPN и интерфейса QML, обеспечивает полное многоуровневое логирование событий (через модуль logging) ''' def __init__(self): '''Инициализация модуля Выполняется инициализация интерфейса, логгера и статуса соединения Определяется операционная система и задаются соответствующие пути ''' self.view = Interface(self) self.logger = logging.getLogger('RocketOne.Connector') self.connected = False # Пути до OpenVPN if os.name == "nt": #Windows paths self.ovpnpath = 'C:\\Program Files (x86)\\OpenVPN' self.path = getBasePath() + '/' self.ovpnconfigpath = self.ovpnpath + '\\config\\' self.configfile = 'config.ini' # self.ovpnconfigpath + self.ovpnexe = self.ovpnpath + '\\bin\\openvpnserv.exe' self.traymsg = 'OpenVPN Connection Manager' self.logger.debug("Started on Windows") elif os.name == "posix": #Linux Paths self.ovpnpath = '' self.path = getBasePath() + '/' self.ovpnconfigpath = self.ovpnpath + '//home//alexei//SOLOWAY//' self.ovpnexe = self.ovpnpath + 'openvpn' self.configfile = 'config.ini' self.traymsg = 'OpenVPN Connection Manager' self.logger.debug("Started on Linux") # Интерфейс обрабатывающий входящие сигналы @QtCore.Slot(str, str) def connect(self, login, passwd): """ Процедура инициализации соединения Является слотом QT (для получения логина и пароля из QML) """ self.port = 0 port = self.getNextAvailablePort() # Если логин и пароль пусты или дефолтные то не соединяемся if (not login) or (not passwd) \ or (login == "Login") or (passwd == "password"): return self.login = login self.password = passwd # если стоит галочка запомнить пароль TODO: убрать конструкцию if self.view.remember(): self.write_settings(login, passwd, remember=True) else: self.write_settings("", "") # Пробуем запустить OpenVPN, не получается - не подключаемся try: self.process = subprocess.Popen([ self.ovpnexe, '--config', self.ovpnconfigpath + 'Soloway.ovpn', '--management', '127.0.0.1', '{0}'.format(port), '--management-query-passwords', '--management-log-cache', '200', '--management-hold' ], cwd=self.ovpnconfigpath) except Exception as e: self.logger.error("OpenVPN process failed to execute " + str(e)) return self.logger.debug("Subprocess started") # Задаем таймер для asyncore loop устанавливаем на 1 раз в секунду self.timer = QTimer() self.timer.connect(SIGNAL("timeout()"), self.looper) self.timer.start(500) self.port = port """ Устанавливаем однократный таймер для запуска обработчика OpenVPN Без таймера openvpn не успевает запуститься, так что при попытке соединения с ним asyncore.async_chat выпадает """ self.atimer = QTimer() self.atimer.setSingleShot(True) self.atimer.timeout.connect(self.manage_process) self.atimer.start(1000) # Записываем время старта, через 20 секунд без подключения - disconnect self.start_time = datetime.now() # Отправляем сигнал в QML о начале соединения self.emit_signal("100") def looper(self): """ looper проверяет не наступил ли таймаут подключения и собирает данные с async_chat. Завязан на таймер self.timer """ ex_time = datetime.now() - self.start_time ex_time = ex_time.total_seconds() if (ex_time > 20) and not self.connected: self.logger.error("Connection time out") self.disconnect("401") asyncore.poll() def manage_process(self): """Запускает обработчик OpenVPN. Выделить в отдельную процедуру пришлось, так как завязан на однократный таймер self.atimer. """ self.sock = ManagementInterfaceHandler(self, '127.0.0.1', self.port) def read_settings(self): """Чтение конфига программы через ConfigParser Если что-то находит - записывает во внутренние переменные """ self.config = ConfigParser() self.config.read(self.configfile) if not self.config.has_section('Auth'): return login = self.config.get('Auth', 'User') password = self.config.get('Auth', 'Password') if self.config.has_section('Options'): remember = self.config.get('Options', 'Remember') self.view.set_remember(remember) else: self.view.set_remember(False) if login and password: self.view.set_auth(login, password) self.login = login self.password = password def write_settings(self, login, passwd, remember=False): """Запись конфига программы""" self.config = ConfigParser() self.config.add_section("Auth") self.config.set("Auth", "User", login) self.config.set("Auth", "Password", passwd) self.config.add_section("Options") self.config.set("Options", "Remember", remember) with open(self.configfile, 'wb') as configfile: self.config.write(configfile) @QtCore.Slot(str) def disconnect(self, status="400"): """Прекращение соединения и придание забвению всех процессов и обработчиков (если они есть конечно) """ self.logger.debug("Shutting down connection") self.port = 0 self.emit_signal(status) if hasattr(self, "timer"): if self.timer: self.timer.stop() self.timer = None if hasattr(self, "sock"): if self.sock: self.sock.send('signal SIGTERM\n') self.sock = None # уничтожает процесс если он еще не уничтожен if hasattr(self, "process") and self.process: try: self.process.terminate() except WindowsError: self.logger.info("Process has been destroyed correctly") self.process = None def emit_signal(self, status): """Отправка сигнала в дальний космос (интерфейс QML) """ self.logger.debug("Emit signal " + status) self.view.emit_signal(status) if status == "200": """Значит подключение было совершено и можно сделать запись в журнале и спрятать окошко в трей. И пусть весь мир подождет.... """ self.logger.debug("Connection initiated") self.connected = True def got_log_line(self, line): """Called from ManagementInterfaceHandler when new log line is received.""" pass def got_state_line(self, line): """Called from ManagementInterfaceHandler when new line describing current OpenVPN's state is received.""" list = line.split(',', 2) state = list[1] if state == 'CONNECTED': self.emit_signal("200") elif state == 'TCP_CONNECT': self.emit_signal("102") elif state == 'AUTH': self.emit_signal("103") elif state == 'GET_CONFIG': self.emit_signal("104") elif state == 'ASSIGN_IP': self.emit_signal("105") #Мясцо def getNextAvailablePort(self): """Returns next minimal unused port starting from 10598.""" minport = 10598 found = False while not found: found = True if self.port != 0: if self.port == minport: found = False minport += 1 break return minport
def Preferences(): """Function to define a first preferences file""" config = ConfigParser() # General config.add_section("General") config.set("General", "Color_Resaltado", "#ffff00") config.set("General", "Color_ReadOnly", "#eaeaea") config.set("General", "Recent_Files", "10") config.set("General", "Load_Last_Project", "True") config.set("General", "Tray", "False") # PFD config.add_section("PFD") config.set("PFD", "x", "800") config.set("PFD", "y", "600") config.set("PFD", "Color_Entrada", "#c80000") config.set("PFD", "Color_Salida", "#0000c8") config.set("PFD", "Color_Stream", "#000000") config.set("PFD", "Width", "1.0") config.set("PFD", "Union", "0") config.set("PFD", "Miter_limit", "2.0") config.set("PFD", "Punta", "0") config.set("PFD", "Guion", "0") config.set("PFD", "Dash_offset", "0.0") # Tooltip config.add_section("Tooltip") config.set("Tooltip", "Show", "True") for i, magnitud in enumerate(magnitudes[:-1]): config.set("Tooltip", magnitud, "[0,1]") # TooltipEntity config.add_section("TooltipEntity") config.set("TooltipEntity", "Corriente", "[0,1]") for equipo in equipos: config.set("TooltipEntity", equipo, "[0,1]") # NumericFactor config.add_section("NumericFormat") for magnitud in magnitudes: kwarg = {'total': 0, 'signo': False, 'decimales': 4, 'format': 0} config.set("NumericFormat", magnitud, str(kwarg)) # Petro config.add_section("petro") config.set("petro", "molecular_weight", "0") config.set("petro", "critical", "0") config.set("petro", "vc", "0") config.set("petro", "f_acent", "0") config.set("petro", "t_ebull", "0") config.set("petro", "Zc", "0") config.set("petro", "PNA", "0") config.set("petro", "H", "0") config.set("petro", "curva", "0") # Applications config.add_section("Applications") config.set("Applications", "Calculator", calculator) config.set("Applications", "TextViewer", editor) config.set("Applications", "Shell", shell) config.set("Applications", "ipython", False) config.set("Applications", "maximized", False) config.set("Applications", "foregroundColor", "#ffffff") config.set("Applications", "backgroundColor", "#000000") # mEoS config.add_section("MEOS") config.set("MEOS", "coolprop", "False") config.set("MEOS", "refprop", "False") config.set("MEOS", "saturation" + "Color", "#000000") config.set("MEOS", "saturation" + "lineWidth", "1.0") config.set("MEOS", "saturation" + "lineStyle", "-") config.set("MEOS", "saturation" + "marker", "None") config.set("MEOS", "grid", "False") config.set("MEOS", "definition", "1") lineas = [ "Isotherm", "Isobar", "Isoenthalpic", "Isoentropic", "Isochor", "Isoquality" ] for linea in lineas: config.set("MEOS", linea + "Start", "0") config.set("MEOS", linea + "End", "0") config.set("MEOS", linea + "Step", "0") config.set("MEOS", linea + "Custom", "True") config.set("MEOS", linea + "List", "") if linea != "Isoquality": config.set("MEOS", linea + "Critic", "True") config.set("MEOS", linea + "Color", "#000000") config.set("MEOS", linea + "lineWidth", "0.5") config.set("MEOS", linea + "lineStyle", "-") config.set("MEOS", linea + "marker", "None") config.set("MEOS", linea + "Label", "False") config.set("MEOS", linea + "Variable", "False") config.set("MEOS", linea + "Units", "False") config.set("MEOS", linea + "Position", "50") # Psychr config.add_section("Psychr") config.set("Psychr", "chart", "True") config.set("Psychr", "virial", "False") config.set("Psychr", "coolprop", "False") config.set("Psychr", "refprop", "False") config.set("Psychr", "saturation" + "Color", "#000000") config.set("Psychr", "saturation" + "lineWidth", "0.5") config.set("Psychr", "saturation" + "lineStyle", "-") config.set("Psychr", "saturation" + "marker", "None") lineas = ["IsoTdb", "IsoW", "IsoHR", "IsoTwb", "Isochor"] values = [{ "start": 274.0, "end": 330.0, "step": 1.0, "color": "#000000", "linewidth": 0.5, "linestyle": ":", "label": "False", "units": "False", "position": 50 }, { "start": 0.0, "end": 0.04, "step": 0.001, "color": "#000000", "linewidth": 0.5, "linestyle": ":", "label": "False", "units": "False", "position": 50 }, { "start": 10.0, "end": 100.0, "step": 10.0, "color": "#000000", "linewidth": 0.5, "linestyle": "--", "label": "True", "units": "True", "position": 85 }, { "start": 250.0, "end": 320.0, "step": 1.0, "color": "#aa0000", "linewidth": 0.8, "linestyle": ":", "label": "False", "units": "False", "position": 90 }, { "start": 0.8, "end": 1.0, "step": 0.01, "color": "#00aa00", "linewidth": 0.8, "linestyle": ":", "label": "False", "units": "False", "position": 90 }] for linea, value in zip(lineas, values): config.set("Psychr", linea + "Start", value["start"]) config.set("Psychr", linea + "End", value["end"]) config.set("Psychr", linea + "Step", value["step"]) config.set("Psychr", linea + "Custom", "False") config.set("Psychr", linea + "List", "") config.set("Psychr", linea + "Color", value["color"]) config.set("Psychr", linea + "lineWidth", value["linewidth"]) config.set("Psychr", linea + "lineStyle", value["linestyle"]) config.set("Psychr", linea + "marker", "None") config.set("Psychr", linea + "Label", value["label"]) config.set("Psychr", linea + "Units", value["units"]) config.set("Psychr", linea + "Position", value["position"]) return config
def config(): """Function to define a first project config file""" config = ConfigParser() # Components config.add_section("Components") config.set("Components", "Components", "[]") config.set("Components", "Solids", "[]") # Thermodynamics config.add_section("Thermo") config.set("Thermo", "K", "0") config.set("Thermo", "Alfa", "0") config.set("Thermo", "Mixing", "0") config.set("Thermo", "H", "0") config.set("Thermo", "Cp_ideal", "0") config.set("Thermo", "MEoS", "False") config.set("Thermo", "iapws", "False") config.set("Thermo", "GERG", "False") config.set("Thermo", "freesteam", "False") config.set("Thermo", "coolProp", "False") config.set("Thermo", "refprop", "False") # Transport config.add_section("Transport") config.set("Transport", "RhoL", "0") config.set("Transport", "Corr_RhoL", "0") config.set("Transport", "MuL", "0") config.set("Transport", "Corr_MuL", "0") config.set("Transport", "MuG", "0") config.set("Transport", "Tension", "0") config.set("Transport", "ThCondL", "0") config.set("Transport", "Corr_ThCondL", "0") config.set("Transport", "ThCondG", "0") config.set("Transport", "Pv", "0") # Units config.add_section("Units") config.set("Units", "System", "0") for magnitud in magnitudes[:-1]: config.set("Units", magnitud, "0") # Resolution config.add_section("PFD") config.set("PFD", "x", "600") config.set("PFD", "y", "480") return config
def run(self): for arg in sys.argv: if "--install-data" in arg: break else: # -------------------------------- # hasattr(sys,'real_prefix') checks whether the # user is working in python virtual environment # -------------------------------- # Modified by @gcasella to use the function created on lines 20-25. if venv_check() is True: self.install_data = os.path.join(sys.prefix, "etc", "jsnapy") elif "win32" in sys.platform: self.install_data = os.path.join(os.path.expanduser("~"), "jsnapy") else: self.install_data = "/etc/jsnapy" dir_path = self.install_data mode = 0o777 install.run(self) # Modified by @gcasella to use the function created on lines 20-25. if "win32" not in sys.platform and not venv_check(): dir_mode = 0o755 file_mode = 0o644 os.chmod(dir_path, dir_mode) for root, dirs, files in os.walk(dir_path): for fname in files: os.chmod(os.path.join(root, fname), file_mode) os.chmod("/var/log/jsnapy", mode) for root, dirs, files in os.walk("/var/log/jsnapy"): for directory in dirs: os.chmod(os.path.join(root, directory), mode) for fname in files: os.chmod(os.path.join(root, fname), mode) # mode = 0o755 # HOME = expanduser("~") # correct cross platform way to do it # home_folder = os.path.join(HOME, '.jsnapy') # if not os.path.isdir(home_folder): # os.mkdir(home_folder) # os.chmod(home_folder, mode) if "JSNAPY_HOME" in os.environ: dir_path = os.environ["JSNAPY_HOME"] if dir_path != "/etc/jsnapy": config = ConfigParser() config.set("DEFAULT", "config_file_path", dir_path) config.set("DEFAULT", "snapshot_path", os.path.join(dir_path, "snapshots")) config.set("DEFAULT", "test_file_path", os.path.join(dir_path, "testfiles")) # Modified by @gcasella to use the function created on lines 20-25. if venv_check() is True: default_config_location = os.path.join(sys.prefix, "etc", "jsnapy", "jsnapy.cfg") elif "win32" in sys.platform: default_config_location = os.path.join(expanduser("~"), "jsnapy", "jsnapy.cfg") else: default_config_location = "/etc/jsnapy/jsnapy.cfg" if os.path.isfile(default_config_location): with open(default_config_location, "w") as cfgfile: comment = ("# This file can be overwritten\n" "# It contains default path for\n" "# config file, snapshots and testfiles\n" "# If required, overwrite the path with" "# your path\n" "# config_file_path: path of main" "# config file\n" "# snapshot_path : path of snapshot file\n" "# test_file_path: path of test file\n\n") cfgfile.write(comment) config.write(cfgfile) else: raise Exception("jsnapy.cfg not found at " + default_config_location) # Modified by @gcasella to use the function created on lines 20-25. if venv_check() is True: path = os.path.join(sys.prefix, "etc", "jsnapy", "logging.yml") set_logging_path(path) elif "win32" in sys.platform: path = os.path.join(expanduser("~"), "jsnapy", "logging.yml") set_logging_path(path)
class SettingWin(tk.Frame): def __init__(self, master): tk.Frame.__init__(self) self.top = tk.Toplevel() self.top.resizable(False, False) self.top.geometry(set_size(self.top, 230, 330)) self.top.title("Default settings") self.default_type = tk.StringVar() self.default_size = tk.IntVar() self.default_filetype = tk.StringVar() self.default_dir = tk.StringVar() self.ean13 = tk.StringVar() self.ean08 = tk.StringVar() self.ean05 = tk.StringVar() self.frameMain = ttk.Frame(self.top) self.frameMain.grid(row=0, column=0, sticky='nswe', padx=(10,0)) self.bottom = ttk.Frame(self.top) self.bottom.grid(row=1, column=0, sticky='nswe', padx=(10,0)) self.bottom.columnconfigure(0, weight=1) self.bottom.columnconfigure(1, weight=1) ttk.Label(self.frameMain, text='Barcode type: ').grid(row=0, column=0, sticky='w', pady=(5,0)) options = ['EAN-13', 'EAN-8', 'EAN-5'] self.dbctype = ttk.OptionMenu(self.frameMain, self.default_type, options[0], *options, style = 'raised.TMenubutton') self.dbctype.config(width=7) self.dbctype.grid(row=0, column=1, pady=(5,0), sticky='we') ttk.Label(self.frameMain, text="Barcode size: ").grid(row=1, column=0, sticky='w', pady=(5,0)) self.dbcsize = tk.Spinbox(self.frameMain, wrap=True, width=5, from_=1, to=10, textvariable=self.default_size); self.dbcsize.grid(row=1, column=1, pady=(5,0), sticky='e') ttk.Label(self.frameMain, text="Default file type:").grid(row=2, column=0, sticky='w', pady=(5,0)) filetypes = ['PDF', 'PNG', 'JPG', 'GIF'] self.dcfiletype = ttk.OptionMenu(self.frameMain, self.default_filetype, filetypes[0], *filetypes) self.dcfiletype.config(width=7) self.dcfiletype.grid(row=2, column=1, sticky='we', pady=(5,0)) ttk.Label(self.frameMain, text='EAN-13 initial value:').grid(row=3, column=0, columnspan=2, sticky='w', pady=(5,0)) self.dean13 = ttk.Entry(self.frameMain, width=26, textvariable=self.ean13) self.dean13.grid(row=4, column=0, columnspan=2) ttk.Label(self.frameMain, text='EAN-08 initial value:').grid(row=5, column=0, columnspan=2, sticky='w', pady=(5,0)) self.dean08 = ttk.Entry(self.frameMain, width=26, textvariable=self.ean08) self.dean08.grid(row=6, column=0, columnspan=2) ttk.Label(self.frameMain, text='EAN-05 initial value:').grid(row=7, column=0, columnspan=2, sticky='w', pady=(5,0)) self.dean05 = ttk.Entry(self.frameMain, width=26, textvariable=self.ean05) self.dean05.grid(row=8, column=0, columnspan=2) self.framepdf = ttk.Frame(self.frameMain) self.framepdf.grid(row=9, column=0, columnspan=2) ttk.Label(self.framepdf, text='File saving directory:').grid(row=0, column=0, sticky='w', pady=(5,0)) self.dfiledir = ttk.Entry(self.framepdf, width=20, textvariable=self.default_dir) self.dfiledir.grid(row=1, column=0, padx=(3, 0), pady=(5,0)) self.pdfbtn = ttk.Button(self.framepdf, text='...', width=3, command=self.folder) self.pdfbtn.grid(row=1, column=1, padx=(5, 0), pady=(5, 0)) self.skpSave = ttk.Button(self.bottom, text='Save', command=self.save_list) self.skpSave.grid(row=0, column=0, sticky='we', padx=(0, 5), pady=(10, 3)) self.btcancel = ttk.Button(self.bottom, text='Cancel', command=self.cancel) self.btcancel.grid(row=0, column=1, sticky='we', padx=(5, 0), pady=(10, 3)) self.dbcsize.focus_set() self.top.bind('<Escape>', self.cancel) self.get_from_ini() self.top.grab_set() master.wait_window(self.top) def get_from_ini(self): self.partlist=[] self.config = ConfigParser() self.config.read('config.ini') sect = 'DefaultValues' self.default_type.set(self.config.get(sect, 'Type')) self.default_size.set(self.config.get(sect, 'Size')) self.default_filetype.set(self.config.get(sect, 'FileType')) self.default_dir.set(self.config.get(sect, 'FileDirectory')) self.ean13.set(self.config.get(sect, 'EAN13start')) self.ean08.set(self.config.get(sect, 'EAN08start')) self.ean05.set(self.config.get(sect, 'EAN05start')) def update_list(self): self.name.delete(0, 'end') self.code.delete(0, 'end') self.address.delete(0, 'end') self.dockname.delete(0, 'end') self.pdfaddress.delete(0, 'end') self.name.insert(0, self.compname.get()) self.code.insert(0, self.compcode.get()) self.address.insert(0, self.compaddress.get()) self.dockname.insert(0, self.dock.get()) self.pdfaddress.insert(0, self.pdfdir.get()) def folder(self): dirpath = fdial.askdirectory(mustexist=False, parent=self.master, title='Choose the folder') if dirpath: self.default_dir.set(dirpath) def save_list(self): sect = 'DefaultValues' self.config.set(sect,'Type', self.default_type.get()) self.config.set(sect, 'Size', self.dbcsize.get()) self.config.set(sect, 'FileType', self.default_filetype.get()) self.config.set(sect, 'FileDirectory', self.default_dir.get()) self.config.set(sect, 'EAN13start', self.ean13.get()) self.config.set(sect, 'EAN08start', self.ean08.get()) self.config.set(sect, 'EAN05start', self.ean05.get()) with open('config.ini', 'w') as configfile: self.config.write(configfile) self.top.destroy() def cancel(self, event=None): self.top.destroy()
# Create directory suffix = "_" + str(int(time.time())) cov_dir = tempfile.mkdtemp(suffix, "m2_coverage_") # Create configuration file coveragerc = os.path.join(cov_dir, ".coveragerc") coverage = os.path.join(cov_dir, ".coverage") from ConfigParser import ConfigParser from os.path import expanduser config = ConfigParser() config.read(['/etc/coveragerc', expanduser('~/.coveragerc')]) if not config.has_section('run'): config.add_section('run') config.set('run', 'data_file', coverage) config.write(open(coveragerc, 'w')) # Add arguments to tests command line testset.add_additionnal_args( ["-m", "coverage", "run", "--rcfile", coveragerc, "-a"]) # Inform the user d = { "blue": cosmetics.colors['blue'], "end": cosmetics.colors['end'], "cov_dir": cov_dir } print "[%(blue)sCoverage%(end)s] Report will be written in %(cov_dir)s" % d # Handle llvm modularity
def set(self, section, option, value=None): section_str = to_utf8(section) option_str = to_utf8(option) value_str = to_utf8(value) if value is not None else '' ConfigParser.set(self, section_str, option_str, value_str)
cf.remove_section('install') else: print('#' * 80) print('') print('Carbon\'s default installation prefix is "/opt/graphite".') print('') print('To install Carbon in the Python\'s default location run:') print('$ GRAPHITE_NO_PREFIX=True python setup.py install') print('') print('#' * 80) try: cf.add_section('install') except DuplicateSectionError: pass if not cf.has_option('install', 'prefix'): cf.set('install', 'prefix', '/opt/graphite') if not cf.has_option('install', 'install-lib'): cf.set('install', 'install-lib', '%(prefix)s/lib') with open('setup.cfg', 'w') as f: cf.write(f) if os.environ.get('USE_SETUPTOOLS'): from setuptools import setup setup_kwargs = dict(zip_safe=0) else: from distutils.core import setup setup_kwargs = dict()
def _in_process_setup_ring(swift_conf, conf_src_dir, testdir): """ If SWIFT_TEST_POLICY is set: - look in swift.conf file for specified policy - move this to be policy-0 but preserving its options - copy its ring file to test dir, changing its devices to suit in process testing, and renaming it to suit policy-0 Otherwise, create a default ring file. """ conf = ConfigParser() conf.read(swift_conf) sp_prefix = 'storage-policy:' try: # policy index 0 will be created if no policy exists in conf policies = parse_storage_policies(conf) except PolicyError as e: raise InProcessException(e) # clear all policies from test swift.conf before adding test policy back for policy in policies: conf.remove_section(sp_prefix + str(policy.idx)) policy_specified = os.environ.get('SWIFT_TEST_POLICY') if policy_specified: policy_to_test = policies.get_by_name(policy_specified) if policy_to_test is None: raise InProcessException('Failed to find policy name "%s"' % policy_specified) _info('Using specified policy %s' % policy_to_test.name) else: policy_to_test = policies.default _info('Defaulting to policy %s' % policy_to_test.name) # make policy_to_test be policy index 0 and default for the test config sp_zero_section = sp_prefix + '0' conf.add_section(sp_zero_section) for (k, v) in policy_to_test.get_info(config=True).items(): conf.set(sp_zero_section, k, v) conf.set(sp_zero_section, 'default', True) with open(swift_conf, 'w') as fp: conf.write(fp) # look for a source ring file ring_file_src = ring_file_test = 'object.ring.gz' if policy_to_test.idx: ring_file_src = 'object-%s.ring.gz' % policy_to_test.idx try: ring_file_src = _in_process_find_conf_file(conf_src_dir, ring_file_src, use_sample=False) except InProcessException as e: if policy_specified: raise InProcessException('Failed to find ring file %s' % ring_file_src) ring_file_src = None ring_file_test = os.path.join(testdir, ring_file_test) if ring_file_src: # copy source ring file to a policy-0 test ring file, re-homing servers _info('Using source ring file %s' % ring_file_src) ring_data = ring.RingData.load(ring_file_src) obj_sockets = [] for dev in ring_data.devs: device = 'sd%c1' % chr(len(obj_sockets) + ord('a')) utils.mkdirs(os.path.join(_testdir, 'sda1')) utils.mkdirs(os.path.join(_testdir, 'sda1', 'tmp')) obj_socket = eventlet.listen(('localhost', 0)) obj_sockets.append(obj_socket) dev['port'] = obj_socket.getsockname()[1] dev['ip'] = '127.0.0.1' dev['device'] = device dev['replication_port'] = dev['port'] dev['replication_ip'] = dev['ip'] ring_data.save(ring_file_test) else: # make default test ring, 2 replicas, 4 partitions, 2 devices _info('No source object ring file, creating 2rep/4part/2dev ring') obj_sockets = [eventlet.listen(('localhost', 0)) for _ in (0, 1)] ring_data = ring.RingData([[0, 1, 0, 1], [1, 0, 1, 0]], [{ 'id': 0, 'zone': 0, 'device': 'sda1', 'ip': '127.0.0.1', 'port': obj_sockets[0].getsockname()[1] }, { 'id': 1, 'zone': 1, 'device': 'sdb1', 'ip': '127.0.0.1', 'port': obj_sockets[1].getsockname()[1] }], 30) with closing(GzipFile(ring_file_test, 'wb')) as f: pickle.dump(ring_data, f) for dev in ring_data.devs: _debug('Ring file dev: %s' % dev) return obj_sockets
def set_config(section, key, value): config = ConfigParser() path = os.path.split(os.path.realpath(__file__))[0] + '/config/custom.conf' config.read(path) config.set(section, key, value) config.write(open(path, "w"))
class SyncHg(cli.Application): PROGNAME = 'SyncHg' VERSION = synchg.__version__ DESCRIPTION = 'Syncs a remote mercurial repository' ConfigFileName = 'config.ini' def __init__(self, *pargs): super(SyncHg, self).__init__(*pargs) self.config = ConfigParser() def _get_config(self, in_do_config=False): ''' Reads the configuration ''' resources.init('obmarg', 'synchg') self.config = ConfigParser() contents = resources.user.read(self.ConfigFileName) if not contents: if not in_do_config: print "Could not find config file" self.do_config() else: self.config.readfp(resources.user.open(self.ConfigFileName)) name = cli.SwitchAttr( ['n', '--name'], help='The directory name of the repository on the remote. ' 'Uses the local directory name by default') @cli.switch(['-c', '--config']) def do_config(self): ''' Runs through the initial configuration ''' print "Running initial configuration" self._get_config(True) srcdir = default = '' if not self.config.has_section('config'): self.config.add_section('config') try: default = self.config.get('config', 'hgroot') except ConfigParserError: pass while not srcdir: srcdir = raw_input( "Remote source directory? [{0}] ".format(default)) self.config.set('config', 'hgroot', srcdir) if not os.path.exists(resources.user.path): os.makedirs(resources.user.path) self.config.write(resources.user.open(self.ConfigFileName, 'w')) pass def main(self, remote_host, local_path=None): self._get_config() if local_path: local_path = local.cwd / local_path else: local_path = local.cwd if not self.name: self.name = local_path.basename SyncRemote(remote_host, self.name, local_path, self.config.get('config', 'hgroot'))
def get_config_value(config_filename, section, option, default_generator=None, write_default=False): """ Get a setting from a configuration file. If none exists, you can optionally create one. An example config file is the ~/.theanorc file, which may contain: [global] # <-- section floatX = float32 # <-- option (value is 'float32') device = gpu0 [lib] cnmem = 1 [cuda] root=/usr/local/cuda/ :param config_filename: A configuration filename (eg '.theanorc'). Here we enforce the convention that files start with '.', and are stored in the user-home directory. :param section: Section in the config file (as referred by squared brackets: see example above) :param option: The option of interest (see above example) :param default_generator: A function that generates the property if it is not there. :param write_default: Set to true if property was not found and you want to write the default value into the file. :return: The value of the property of interest. """ config_path = get_config_path(config_filename) default_used = False if write_default: assert default_generator is not None, "If you set write_default true, you must provide a function that can generate the default." if not os.path.exists(config_path): assert default_generator is not None, 'No config file "%s" exists, and you do not have any default value.' % ( config_path, ) value = default_generator() default_used = True else: config = ConfigParser() config.read(config_path) try: value = config.get(section, option) except (NoSectionError, NoOptionError) as err: if default_generator is None: raise else: value = default_generator() default_used = True if default_used and write_default: config = ConfigParser() config.read(config_path) if not config.has_section(section): config.add_section(section) config.set(section, option, value) with open(config_path, 'w') as f: config.write(f) return value
def loadFromStream(self, stream, huella=True, run=True): """Read project from stream huella: boolean to save project file to pychemqt_temporal""" # read configuration config = ConfigParser() for i in range(stream.readInt32()): section = stream.readString() config.add_section(section) for contador_option in range(stream.readInt32()): option = stream.readString() valor = stream.readString() config.set(section, option, valor) #TODO: Necesario para cargar los proyectos viejos # config.set("Thermo", "freesteam", "False") config.set("Units", "MolarSpecificHeat", "0") self.setConfig(config) if not huella: os.rename(conf_dir + "pychemqtrc_temporal", conf_dir + "pychemqtrc_temporal_bak") config.write(open(conf_dir + "pychemqtrc_temporal", "w")) # read equipments items = {} contador_equipos = stream.readInt32() for i in range(contador_equipos): id = stream.readString() if id[0] == "e": equip = equipments[stream.readInt32()]() equip.readFromStream(stream, run) else: equip = None items[id] = equip self.setItems(items) # read streams streams = {} contador_streams = stream.readInt32() for item in range(contador_streams): id = stream.readInt32() up = stream.readString() down = stream.readString() ind_up = stream.readInt32() ind_down = stream.readInt32() obj = Corriente() obj.readFromStream(stream, run) streams[id] = (up, down, ind_up, ind_down, obj) if huella: if down[0] == "e": equip = self.items[down] if isinstance(equip, Mixer): kwargs = {"entrada": obj, "id_entrada": ind_down} else: kwargs = {equip.kwargsInput[ind_down]: obj} equip(**kwargs) self.setStreams(streams) if not huella: os.rename(conf_dir + "pychemqtrc_temporal_bak", conf_dir + "pychemqtrc_temporal")
class StoqdriversConfig: domain = 'stoqdrivers' def __init__(self, filename=None): """ filename is the name of the configuration file we're reading """ self.filename = filename or (self.domain + '.conf') self.config = ConfigParser() self._load_config() def get_homepath(self): return os.path.join(os.getenv('HOME'), '.' + self.domain) def _open_config(self, path): filename = os.path.join(path, self.filename) if not os.path.exists(filename): return False self.config.read(filename) return True def _load_config(self): # Try to load configuration from: # 1) $HOME/.$domain/$filename # 2) $PREFIX/etc/$domain/$filename # 3) /etc/$filename # This is a bit hackish: # $prefix / lib / $DOMAIN / lib / config.py # -4 -3 -2 -1 0 filename = os.path.abspath(__file__) stripped = filename.split(os.sep)[:-4] self.prefix = os.path.join(os.sep, *stripped) homepath = self.get_homepath() etcpath = os.path.join(self.prefix, 'etc', self.domain) globetcpath = os.path.join(os.sep, 'etc', self.domain) if not (self._open_config(homepath) or self._open_config(etcpath) or self._open_config(globetcpath)): raise ConfigError( _("Config file not found in: `%s', `%s' and " "`%s'") % (homepath, etcpath, globetcpath)) def has_section(self, section): return self.config.has_section(section) def has_option(self, name, section='General'): return self.config.has_option(section, name) def get_option(self, name, section='General'): if not self.config.has_section(section): raise ConfigError(_("Invalid section: %s") % section) elif not self.config.has_option(section, name): raise ConfigError( _("%s does not have option: %s") % (self.filename, name)) return self.config.get(section, name) def set_option(self, name, section='General'): if not self.config.has_section(section): raise ConfigError(_("Invalid section: %s") % section) self.config.set(section, name)
# Load the traverser, and get our files. traverser = Upgrader.Traverser(server_data_path) files = traverser.get_files() upgrades_path = "upgrades" print("Running upgrade scripts...") # Go through upgrade scripts. for item in sorted(os.listdir(upgrades_path)): file = upgrades_path + "/" + item if os.path.isfile(file): dot_pos = item.find(".") if dot_pos != -1: # Have we ran this script before? If not, run it now. if not config.has_option("Upgrades", item[:dot_pos]) or not config.getboolean( "Upgrades", item[:dot_pos]): print("\tRunning script: {0}".format(file)) execfile(file) config.set("Upgrades", item[:dot_pos], "true") print("Saving configuration...") # Save the config. with open("config.cfg", "wb") as configfile: config.write(configfile) print("... Finished upgrading!")
def set(self, section, option, value=None): if not ConfigParser.has_section(self, section): ConfigParser.add_section(self, section) return ConfigParser.set(self, section, option, value)
def get_ini(queryset): output = StringIO() config = ConfigParser() providerset = set() for sc in queryset: section = 'servicecode {0}'.format(sc.name) config.add_section(section) config.set(section, 'provider', sc.provider) providerset.add(sc.provider) config.set(section, 'country', sc.provider.country.config_name) config.set(section, 'tariff', sc.tariff) config.set(section, 'currency', sc.currency) for opt in sc.owns.all(): config.set(section, opt.key.name, opt.value) for provider in providerset: section = 'provider {0}'.format(provider.name) config.add_section(section) config.set(section, 'country', provider.country.config_name) config.set(section, 'timeout', provider.timeout) config.set(section, 'adaptor', provider.adaptor) config.set(section, 'cdr_string', provider.cdr_string) extras = provider.specialization.all() for opt in provider.owns.all(): config.set(section, opt.key.name, opt.value) if extras: config.set(section, 'service', ','.join([extra.name for extra in extras])) for extra in extras: x_section = 'extra {0} {1}'.format(provider.name, extra.name) config.add_section(x_section) for opt in extra.owns.all(): config.set(x_section, opt.key.name, opt.value) config.write(output) return output.getvalue()
def set(self, section, option, value): if not self.has_section(section): self.add_section(section) ConfigParser.set(self, section, option, value) self.save_changes()
class PlatformConfig: def __init__(self, config_dir): self.parser = ConfigParser() self.filename = join(config_dir, PLATFORM_CONFIG_NAME) if (not isfile(self.filename)): raise Exception('platform config does not exist: {0}'.format( self.filename)) self.parser.read(self.filename) def apps_root(self): return self.__get('apps_root') def data_root(self): return self.__get('data_root') def configs_root(self): return self.__get('configs_root') def config_root(self): return self.__get('config_root') def www_root_internal(self): return self.__get('www_root_internal') def www_root_public(self): return self.__get('www_root_public') def app_dir(self): return self.__get('app_dir') def data_dir(self): return self.__get('data_dir') def config_dir(self): return self.__get('config_dir') def bin_dir(self): return self.__get('bin_dir') def nginx_config_dir(self): return self.__get('nginx_config_dir') def cron_user(self): return self.__get('cron_user') def cron_cmd(self): return self.__get('cron_cmd') def openssl(self): return self.__get('openssl') def nginx(self): return self.__get('nginx') def cron_schedule(self): return self.__get('cron_schedule') def get_web_secret_key(self): return self.__get('web_secret_key') def set_web_secret_key(self, value): return self.__set('web_secret_key', value) def get_user_config(self): return self.__get('user_config') def get_log_root(self): return self.__get('log_root') def get_log_sender_pattern(self): return self.__get('log_sender_pattern') def get_internal_disk_dir(self): return self.__get('internal_disk_dir') def get_external_disk_dir(self): return self.__get('external_disk_dir') def get_disk_link(self): return self.__get('disk_link') def get_disk_root(self): return self.__get('disk_root') def get_ssh_port(self): return self.__get('ssh_port') def set_ssh_port(self, value): return self.__set('ssh_port', value) def get_rest_internal_log(self): return self.__get('rest_internal_log') def get_rest_public_log(self): return self.__get('rest_public_log') def get_ssl_certificate_file(self): return self.__get('ssl_certificate_file') def get_ssl_ca_certificate_file(self): return self.__get('ssl_ca_certificate_file') def get_ssl_ca_serial_file(self): return self.__get('ssl_ca_serial_file') def get_ssl_certificate_request_file(self): return self.__get('ssl_certificate_request_file') def get_default_ssl_certificate_file(self): return self.__get('default_ssl_certificate_file') def get_ssl_key_file(self): return self.__get('ssl_key_file') def get_ssl_ca_key_file(self): return self.__get('ssl_ca_key_file') def get_default_ssl_key_file(self): return self.__get('default_ssl_key_file') def get_openssl_config(self): return self.__get('openssl_config') def get_platform_log(self): return self.__get('platform_log') def get_installer(self): return self.__get('installer') def get_hooks_root(self): return self.__get('hooks_root') def is_certbot_test_cert(self): return self.parser.getboolean('platform', 'certbot_test_cert') def get_boot_extend_script(self): return self.__get('boot_extend_script') def __get(self, key): return self.parser.get('platform', key) def __set(self, key, value): self.parser.set('platform', key, value) with open(self.filename, 'wb') as f: self.parser.write(f)
#print "test" #for section in config.sections(): #if config.has_option(section, "datasetpath"): #dspath = config.get(section, "datasetpath") #import subprocess as sp #try: #out = sp.check_output("dasgoclient --query 'parent dataset=%s'"%(dspath), shell=True) #if not "PU2017" in out: #print dspath, "wrong PU" #except: #print dspath, "not valid" #print out #exit() trees = readTrees(path) for name, tree in trees.iteritems(): ROOT.gROOT.Reset() print name pos = tree.CopyTree(cutsPos).GetEntries() neg = tree.CopyTree(cutsNeg).GetEntries() print "events with pos. weight: %d" % pos print "events with neg. weight: %d" % neg frac = float(neg) / (neg + pos) print "fraction: %.3f" % (frac) config.set(name, 'negWeightFraction', "%.3f" % (frac)) trees[name] = None with open("newConfig.ini", "w+") as configfile: config.write(configfile)
except IOError: quit("The '%s' file doesn't exist" % MoioSMSfile) MoioSMSconfig = ConfigParser() MoioSMSconfig.optionxform = str MoioSMSconfig.read(MoioSMSfile) try: contacts = MoioSMSconfig.items('contacts') except NoSectionError: quit("The is no such contact stored in your MoioSMS2 file!") # Write contacts into pyMoioSMS configuration file try: file(pyMoioSMSfile) except IOError: quit("The '%s' file doesn't exist" % pyMoioSMSfile) pyMoioSMSconfig = ConfigParser() pyMoioSMSconfig.optionxform = str pyMoioSMSconfig.read(pyMoioSMSfile) pyMoioSMSconfig.add_section('contacts') if not pyMoioSMSconfig.has_section('contacts') else None for key, value in contacts: if pyMoioSMSconfig.has_option('contacts', key): if value == pyMoioSMSconfig.get('contacts', key): print "[!] Skipping '%s' (it already exists here..)" % key else: print "[!] An option called '%s' already exists but having a different number." % key new_key = raw_input("Do you want to add it using a different name? Enter it here now or leave this field empty to skip this contact\n") if new_key: pyMoioSMSconfig.set('contacts', new_key, value) else: print "[!] Skipping '%s'" % key else: pyMoioSMSconfig.set('contacts', key, value) pyMoioSMSconfig.write(open(pyMoioSMSfile, "w")) print "OK! I've successfully parsed %s contacts :)" % len(contacts) elif answer.lower() == 'n': pass else: quit('Not valid command. Quit')
class PlatformUserConfig: def __init__(self, config_file): self.log = logger.get_logger('PlatformUserConfig') self.parser = ConfigParser() self.filename = config_file def update_redirect(self, domain, api_url): self.parser.read(self.filename) self.log.info('setting domain={0}, api_url={1}'.format( domain, api_url)) self.__set('redirect', 'domain', domain) self.__set('redirect', 'api_url', api_url) self.__save() def get_redirect_domain(self): self.parser.read(self.filename) if self.parser.has_section('redirect') and self.parser.has_option( 'redirect', 'domain'): return self.parser.get('redirect', 'domain') return 'syncloud.it' def get_redirect_api_url(self): self.parser.read(self.filename) if self.parser.has_section('redirect') and self.parser.has_option( 'redirect', 'api_url'): return self.parser.get('redirect', 'api_url') return 'http://api.syncloud.it' def set_user_update_token(self, user_update_token): self.parser.read(self.filename) self.__set('redirect', 'user_update_token', user_update_token) self.__save() def get_user_update_token(self): self.parser.read(self.filename) return self.parser.get('redirect', 'user_update_token') def set_user_email(self, user_email): self.parser.read(self.filename) self.__set('redirect', 'user_email', user_email) self.__save() def get_user_email(self): self.parser.read(self.filename) return self.parser.get('redirect', 'user_email') def set_custom_domain(self, custom_domain): self.parser.read(self.filename) self.__set('platform', 'custom_domain', custom_domain) self.__save() def get_custom_domain(self): self.parser.read(self.filename) if self.parser.has_option('platform', 'custom_domain'): return self.parser.get('platform', 'custom_domain') return None def get_user_domain(self): self.parser.read(self.filename) if self.parser.has_option('platform', 'user_domain'): return self.parser.get('platform', 'user_domain') return None def get_domain_update_token(self): self.parser.read(self.filename) if self.parser.has_option('platform', 'domain_update_token'): return self.parser.get('platform', 'domain_update_token') return None def update_domain(self, user_domain, domain_update_token): self.parser.read(self.filename) self.log.info( 'saving user_domain = {0}, domain_update_token = {0}'.format( user_domain, domain_update_token)) self.__set('platform', 'user_domain', user_domain) self.__set('platform', 'domain_update_token', domain_update_token) self.__save() def get_external_access(self): self.parser.read(self.filename) if not self.parser.has_option('platform', 'external_access'): return False return self.parser.getboolean('platform', 'external_access') def is_redirect_enabled(self): self.parser.read(self.filename) if not self.parser.has_option('platform', 'redirect_enabled'): return True return self.parser.getboolean('platform', 'redirect_enabled') def set_redirect_enabled(self, enabled): self.parser.read(self.filename) self.__set('platform', 'redirect_enabled', enabled) self.__save() def update_device_access(self, upnp_enabled, external_access, public_ip, public_port): self.parser.read(self.filename) self.__set('platform', 'external_access', external_access) self.__set('platform', 'upnp', upnp_enabled) self.__set('platform', 'public_ip', public_ip) self.__set('platform', 'manual_public_port', public_port) self.__save() def get_upnp(self): self.parser.read(self.filename) if not self.parser.has_option('platform', 'upnp'): return True return self.parser.getboolean('platform', 'upnp') def get_public_ip(self): self.parser.read(self.filename) if not self.parser.has_option('platform', 'public_ip'): return None return self.parser.get('platform', 'public_ip') def get_manual_public_port(self): self.parser.read(self.filename) if not self.parser.has_option('platform', 'manual_public_port'): return None return self.parser.get('platform', 'manual_public_port') def __set(self, section, key, value): if not self.parser.has_section(section): self.parser.add_section(section) self.parser.set(section, key, value) def __save(self): with open(self.filename, 'wb') as f: self.parser.write(f)
class classConfig(): def __init__(self): # Read config.ini self.Config = ConfigParser() x = 0 y = 0 raio = 0 self.SERVO_PAN = None self.SERVO_TILT = None self.SERVO_PAN_LEFT = None self.SERVO_PAN_RIGHT = None self.SERVO_TILT_VALUE = None self.SERVO_PAN_VALUE = None self.max_count_lost_frame = None self.max_count_lost_frame_far_ball = None self.head_up = None self.cut_edge_image = None self.kernel_perto = None self.kernel_perto2 = None self.kernel_medio = None self.kernel_medio2 = None self.kernel_longe = None self.kernel_longe2 = None self.kernel_muito_longe = None self.kernel_muito_longe2 = None self.x_left = None self.x_center_left = None self.x_center = None self.x_center_right = None self.x_right = None self.y_chute = None self.y_longe = None self.when_ball_up = None self.when_ball_down = None self.CheckConfig() def CheckConfig(self): # Read file config.ini while True: if self.Config.read('../Data/config.ini') != []: print 'Leitura do config.ini' self.CENTER_SERVO_PAN = self.Config.getint( 'Basic Settings', 'center_servo_pan') self.POSITION_SERVO_TILT = self.Config.getint( 'Basic Settings', 'position_servo_tilt') self.SERVO_PAN_LEFT = self.Config.getint( 'Basic Settings', 'servo_pan_left') self.SERVO_PAN_RIGHT = self.Config.getint( 'Basic Settings', 'servo_pan_right') self.SERVO_PAN_ID = self.Config.getint('Basic Settings', 'PAN_ID') self.SERVO_TILT_ID = self.Config.getint( 'Basic Settings', 'TILT_ID') self.DNN_folder = self.Config.get('Basic Settings', 'dnn_folder') self.max_count_lost_frame = self.Config.getint( 'Basic Settings', 'max_count_lost_frame') self.max_count_lost_frame_far_ball = self.Config.getint( 'Basic Settings', 'max_count_lost_frame_far_ball') self.head_up = self.Config.getint('Basic Settings', 'head_up') self.cut_edge_image = self.Config.getint( 'Basic Settings', 'cut_edge_image') self.x_left = self.Config.getint('Distance Limits (Pixels)', 'Left_Region_Division') self.x_center = self.Config.getint('Distance Limits (Pixels)', 'Center_Region_Division') self.x_right = self.Config.getint('Distance Limits (Pixels)', 'Right_Region_Division') self.y_chute = self.Config.getint('Distance Limits (Pixels)', 'Down_Region_Division') self.y_longe = self.Config.getint('Distance Limits (Pixels)', 'Up_Region_Division') self.when_ball_up = self.Config.getint( 'Distance Limits (Pixels)', 'when_ball_up') self.when_ball_down = self.Config.getint( 'Distance Limits (Pixels)', 'when_ball_down') break else: print 'Falha na leitura do config.ini, criando arquivo\nVision Ball inexistente, criando valores padrao' self.Config = ConfigParser() self.Config.write('../Data/config.ini') self.Config.add_section('Basic Settings') self.Config.set('Basic Settings', 'center_servo_pan', str(512) + '\t\t\t;Center Servo PAN Position') self.Config.set('Basic Settings', 'position_servo_tilt', str(705) + '\t;Center Servo TILT Position') self.Config.set('Basic Settings', 'servo_pan_left', str(162) + '\t\t\t;Center Servo PAN Position') self.Config.set('Basic Settings', 'servo_pan_right', str(862) + '\t;Center Servo TILT Position') self.Config.set( 'Basic Settings', 'PAN_ID', str(19) + '\t\t\t;Servo Identification number for PAN') self.Config.set( 'Basic Settings', 'TILT_ID', str(20) + '\t;Servo Identification number for TILT') self.Config.set('Basic Settings', 'dnn_folder', "rede" + '\t;Dnn folder') self.Config.set('Basic Settings', 'max_count_lost_frame', str(10) + '\t;Threshould') self.Config.set( 'Basic Settings', 'max_count_lost_frame_far_ball', str(30) + '\t;Quanto que o robo espera apos achar a bola de longe') self.Config.set( 'Basic Settings', 'head_up', str(70) + '\t;Quanto que a cabeca sobe quando bola esta acima') self.Config.set( 'Basic Settings', 'cut_edge_image', str(150) + '\t;Corta as bordas pretas da imagem') self.Config.add_section('Distance Limits (Pixels)') self.Config.set('Distance Limits (Pixels)', 'Left_Region_Division', str(280) + '\t\t\t;X Screen Left division') self.Config.set('Distance Limits (Pixels)', 'Center_Region_Division', str(465) + '\t\t\t;X Screen Center division') self.Config.set('Distance Limits (Pixels)', 'Right_Region_Division', str(703) + '\t\t\t;X Screen Right division') self.Config.set('Distance Limits (Pixels)', 'Down_Region_Division', str(549) + '\t\t\t;Y Screen Down division') self.Config.set('Distance Limits (Pixels)', 'Up_Region_Division', str(220) + '\t\t\t;Y Screen Up division') self.Config.set( 'Distance Limits (Pixels)', 'when_ball_up', str(222) + '\t\t\t;Y screen for ball on up screen') self.Config.set( 'Distance Limits (Pixels)', 'when_ball_dpwn', str(333) + '\t\t\t;Y screen for ball on down screen') with open('../Data/config.ini', 'wb') as configfile: self.Config.write(configfile)
def savePreferencesFile(filename=None, prefToSave=None): """Saves the Preferences settings to a Preferences file. @param filename: if not None, the name of the file where to save the preferences otherwise the file name will be set to an OS dependant location: -$USERPROFILE/Application Data/nMOLDYN/nMOLDYN.ini on Windows -$HOME/Library/Preferences/nMLDYN/nMOLDYN.pref on MacOS -$HOME/.nMOLDYN on Linux @type filename: string. @param prefToSave: the preferences to save. If None, the default preferences will be saved. @type prefToLoad: instance of a dummy class whose attributes must be the nMOLDYN preferences variable names. """ prefs = copy.copy(PREFERENCES) prefs.update(prefToSave) # If no file name was given as input, constructs an arbitrary OS-dependant one. if filename is None: try: # Case of Win32. if PLATFORM == 'WINDOWS': directory = os.path.join(os.environ['USERPROFILE'], 'Application Data', 'nMOLDYN') filename = os.path.abspath( os.path.join(directory, 'nMOLDYN.ini')) # Case of Mac OS. elif PLATFORM == 'DARWIN': directory = os.path.join(os.environ['HOME'], 'Library', 'Preferences', 'nMOLDYN') filename = os.path.abspath( os.path.join(directory, 'nMOLDYN.pref')) # Case of Linux. else: directory = os.environ['HOME'] filename = os.path.abspath(os.path.join(directory, '.nMOLDYN')) # The file name could not be built. Raises an error. except KeyError: raise Error( 'Invalid default location for the nMOLDYN configuration file.') # The file name could be built. else: # Checks that the directory where the preferences file will be saved exists. If not, creates it. if not os.path.exists(directory): os.makedirs(directory) # Tries to open the preferences file for writing. try: prefFile = open(filename, 'w') # The file could not be opened. Raises an error. except IOError: raise Error( 'Impossible to open the file %s for writing. May be a permission problem.' % filename) # The file could be opened. else: # Sets up an instance of configuration parser. cfg = ConfigParser() # Creates a section called 'nmoldyn'. cfg.add_section('nmoldyn') # Loops over the nMOLDYN preferences variables. for k, v in prefs.items(): if not v: cfg.set('nmoldyn', k, 'undefined') else: cfg.set('nmoldyn', k, v) # Write the configuration parser into the preferences file. cfg.write(prefFile) # Close the preferences file. prefFile.close()
def to_file(cls, cfg, file_name=None): """ Writes a Config to a file. """ if file_name is None: if cfg.file_name is None: file_name = os.path.expanduser(DEFAULT_CFG_PATH) else: file_name = cfg.file_name file_name = os.path.expanduser(file_name) parser = ConfigParser() # MUST do this or directory names get mangled. # IMPORTANT: Turn off downcasing of option names. parser.optionxform = str parser.add_section('primary') parser.set('primary', 'format_version', FORMAT_VERSION) parser.set('primary', 'host', cfg.defaults['HOST']) parser.set('primary', 'port', cfg.defaults['PORT']) parser.set('primary', 'tmp_dir', cfg.defaults['TMP_DIR']) parser.set('primary', 'default_private_key', cfg.defaults['DEFAULT_PRIVATE_KEY']) parser.set('primary', 'fms_host', cfg.defaults['FMS_HOST']) parser.set('primary', 'fms_port', cfg.defaults['FMS_PORT']) parser.set('primary', 'fms_id', cfg.defaults['FMS_ID']) parser.set('primary', 'fmsnotify_group', cfg.defaults['FMSNOTIFY_GROUP']) parser.set('primary', 'fmsread_groups', '|'.join(cfg.fmsread_groups)) parser.set('primary', 'default_truster', cfg.defaults['DEFAULT_TRUSTER']) parser.add_section('index_values') for repo_id in cfg.version_table: parser.set('index_values', repo_id, cfg.version_table[repo_id]) parser.add_section('request_usks') for repo_dir in cfg.request_usks: parser.set('request_usks', repo_dir, cfg.request_usks[repo_dir]) parser.add_section('insert_usks') for repo_id in cfg.insert_usks: parser.set('insert_usks', repo_id, cfg.insert_usks[repo_id]) parser.add_section('wot_identities') for repo_id in cfg.wot_identities: parser.set('wot_identities', repo_id, cfg.wot_identities[repo_id]) parser.add_section('freemail_passwords') for wot_id in cfg.freemail_passwords: parser.set('freemail_passwords', wot_id, cfg.freemail_passwords[ wot_id]) parser.add_section('repo_list_editions') for wot_id in cfg.repo_list_editions: parser.set('repo_list_editions', wot_id, cfg.repo_list_editions[ wot_id]) parser.add_section('fmsread_trust_map') for index, fms_id in enumerate(cfg.fmsread_trust_map): entry = cfg.fmsread_trust_map[fms_id] assert len(entry) > 0 parser.set('fmsread_trust_map', str(index), fms_id + '|' + '|'.join(entry)) out_file = open(file_name, 'wb') try: parser.write(out_file) finally: out_file.close()
txtOutPaths.append(application.getTxtOutPath()) if generateTSV: from Meta import Meta print "Generating TSV (.dat) files..." Meta(popmetabinpath=pypopbinpath, datapath=datapath, metaXSLTDirectory=None, dump_meta=0, R_output=1, PHYLIP_output=0, ihwg_output=1, batchsize=len(xmlOutPaths), files=xmlOutPaths) if interactiveFlag: print "PyPop run complete!" print "XML output(s) can be found in: ", xmlOutPaths print "Plain text output(s) can be found in: ", txtOutPaths # update .pypoprc file if pypoprc.has_section('Files') != 1: pypoprc.add_section('Files') pypoprc.set('Files', 'config', os.path.abspath(configFilename)) pypoprc.set('Files', 'pop', os.path.abspath(fileNames[0])) pypoprc.write(open(pypoprcFilename, 'w'))
def createNodeInfoFile(dirPath, toKeep): """ Creates the .nodeInfo file in the directory specified by dirPath. The Node:Type must be set by concrete nodes @precondition: dirPath is a valid directory @postcondition: All sections/tags are created and set except "Type". "Type" must be set by concrete nodes. """ print "in createNodeInfoFile" username = amu.getUsername() timestamp = time.strftime("%a, %d %b %Y %I:%M:%S %p", time.localtime()) nodeInfo = ConfigParser() nodeInfo.add_section('Node') nodeInfo.set('Node', 'Type', '') nodeInfo.add_section('Versioning') nodeInfo.set('Versioning', 'LatestVersion', '0') nodeInfo.set('Versioning', 'VersionsToKeep', str(toKeep)) nodeInfo.set('Versioning', 'Locked', 'False') nodeInfo.set('Versioning', 'LastCheckoutTime', timestamp) nodeInfo.set('Versioning', 'LastCheckoutUser', username) nodeInfo.set('Versioning', 'LastCheckinTime', timestamp) nodeInfo.set('Versioning', 'LastCheckinUser', username) nodeInfo.add_section('Comments') nodeInfo.set('Comments', 'v000', 'New') amu._writeConfigFile(os.path.join(dirPath, ".nodeInfo"), nodeInfo)
class Config(object): def __init__(self, inifile='data/config.ini'): self.inifile = inifile self.cfg = ConfigParser() with FileLock(inifile): if os.path.exists(inifile): self.cfg.read(inifile) # initialize configurations default_configs = { 'server': { 'ip': '*', 'port': '8888', 'lastcheckupdate': 0, 'updateinfo': '' }, 'auth': { 'username': '******', 'password': '', # empty password never validated 'passwordcheck': 'on', 'accesskey': '', # empty access key never validated 'accesskeyenable': 'off', }, 'runtime': { 'mode': '', # format: demo | dev | prod 'loginlock': 'off', 'loginfails': 0, 'loginlockexpire': 0, }, 'file': { 'lastdir': '/root', 'lastfile': '', }, 'time': { 'timezone': '' # format: timezone = Asia/Shanghai }, 'ecs': { 'accounts': '' }, 'inpanel': { # format: Instance Name = Access key } } needupdate = False for sec, secdata in default_configs.iteritems(): if not self.cfg.has_section(sec): self.cfg.add_section(sec) needupdate = True for opt, val in secdata.iteritems(): if not self.cfg.has_option(sec, opt): self.cfg.set(sec, opt, val) needupdate = True # update ini file if needupdate: self.update(False) def update(self, lock=True): if lock: flock = FileLock(self.inifile) flock.acquire() try: inifp = open(self.inifile, 'w') self.cfg.write(inifp) inifp.close() if lock: flock.release() return True except: if lock: flock.release() return False def has_option(self, section, option): return self.cfg.has_option(section, option) def get(self, section, option): return self.cfg.get(section, option) def getboolean(self, section, option): return self.cfg.getboolean(section, option) def getint(self, section, option): return self.cfg.getint(section, option) def has_section(self, section): return self.cfg.has_section(section) def add_section(self, section): return self.cfg.add_section(section) def remove_option(self, section, option): return self.cfg.remove_option(section, option) def set(self, section, option, value): try: self.cfg.set(section, option, value) except: return False return self.update()