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 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 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()
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 create_file_conf(conf_path): # create config file fp = open(conf_path, 'w') from ConfigParser import ConfigParser config = ConfigParser() config.add_section('application') config.set('application', 'auto_login_swittch', False) config.set('application', 'auto_update', True) config.set('application', 'startup_on_boot', True) config.set('application', 'auto_update',True) config.set('application', 'auto_update_test_mod', True) config.add_section('logging') config.set('logging', 'log_level', 'INFO') config.add_section('network') config.set('network', 'max_speer_num', 10) config.set('network', 'max_peer_num', 15) config.set('network', 'max_conn_num', 100) config.set('network', 'listen_port', 5895) config.add_section('web') config.set('web', 'listen_port', 8080) config.set('network', 'aggregator_url', 'http://alpha.openmonitor.org') config.set('application', 'selected_tests', '') config.write(fp) fp.close()
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 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)
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 _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 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 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)
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 setup_pypi(pypi, extras=None, strict=False): # setup distutils.cfg import distutils location = os.path.dirname(distutils.__file__) cfg = os.path.join(location, 'distutils.cfg') if os.path.exists(cfg): os.remove(cfg) parser = ConfigParser() parser.read(cfg) if 'easy_install' not in parser.sections(): parser.add_section('easy_install') parser.set('easy_install', 'index_url', pypi) allowed_hosts = [urlparse(pypi)[1]] if extras: parser.set('easy_install', 'find_links', extras) allowed_hosts.append(urlparse(extras)[1]) if strict: parser.set('easy_install', 'allow_hosts', ','.join(allowed_hosts)) with open(cfg, 'w') as cfg: parser.write(cfg)
def startCompetitorDialog(self): pbText = str(self.startStopPB.text()) if pbText == "Start": self.newCompetitorDialog.show() if pbText == "Stop": self.timer.stop() self.updateStartStop("Start") log = ConfigParser() log.add_section("Scoreboard") log.set("Scoreboard","MinesDetected",self.mineDetectedLB.text()) log.set("Scoreboard","WrongMinesDetected",self.wrongMinesDetectedLB.text()) log.set("Scoreboard","ExplodedMines",len(self.minesExploded)) log.set("Scoreboard","ExplodedMinesDetected",len(self.minesExplodedDetected)) log.set("Scoreboard","Time",self.timeLB.text()) undetected = undetectedCovered = 0 mWidth, mHeight = self.width/self.cellXSize,self.height/self.cellYSize for m in self.mines: if not self.minesDetected.has_key(tuple(m)): x, y = m[0]/self.cellXSize+mWidth/2., mHeight/2. - m[1]/self.cellYSize if (x<0) or (y<0) or (y >self.Map.shape[0]) or (x >self.Map.shape[1]): undetected += 1 continue if self.actionCoilsSignal.isChecked(): if self.Map[y,x] != 220: undetectedCovered += 1 else: undetected += 1 else: if self.Map[y,x] == 183: undetectedCovered += 1 else: undetected += 1 log.set("Scoreboard","Undetected", undetected) log.set("Scoreboard","UndetectedCovered", undetectedCovered) percent = 0.0 if self.actionCoilsSignal.isChecked(): percent = self.Map[self.Map != 220].size/float(self.Map.size) else: percent = self.Map[self.Map == 183].size/float(self.Map.size) log.set("Scoreboard","Covered Area",percent) path = os.path.expanduser("~/HRATC 2014 Simulator/") if not os.path.exists(path): os.mkdir(path) path += "logs/" if not os.path.exists(path): os.mkdir(path) cfile = open(path+"/log_{}.log".format(self.competitorName),"w") log.write(cfile) cfile.close() self.competitorName = None
def _upload_credentials(aws_config, manager_config_path): temp_config = tempfile.mktemp() credentials = ConfigParser() credentials.add_section('Credentials') credentials.set('Credentials', 'aws_access_key_id', aws_config['aws_access_key_id']) credentials.set('Credentials', 'aws_secret_access_key', aws_config['aws_secret_access_key']) if aws_config.get('ec2_region_name'): region = get_region(aws_config['ec2_region_name']) credentials.add_section('Boto') credentials.set('Boto', 'ec2_region_name', aws_config['ec2_region_name']) credentials.set('Boto', 'ec2_region_endpoint', region.endpoint) credentials_string = StringIO() credentials.write(credentials_string) with open(temp_config, 'w') as temp_config_file: temp_config_file.write(credentials_string.getvalue()) make_default_lower = \ 'sed -i "s/\[DEFAULT\]/\[default\]/g" {0}'.format( constants.AWS_DEFAULT_CONFIG_PATH) fabric.api.put(temp_config, manager_config_path) fabric.api.run(make_default_lower)
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)
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 build_root_cfg(root, timeout, keys): # construct the configuration file parser (hint: .ini) cp = ConfigParser() # handle the expiration data cp.add_section("expiration") cp.set("expiration", "days", timeout) cp.set("expiration", "years", 0) cp.set("expiration", "minutes", 0) cp.set("expiration", "hours", 0) cp.set("expiration", "seconds", 0) # build the role data for role in keys: cp.add_section(role) # each role has an associated list of key id's and a threshold key_ids, threshold = keys[role] # convert the key_ids stuff into a list it can read id_list = ",".join(key_ids) # and add that data to the appropriate section cp.set(role, "keyids", id_list) cp.set(role, "threshold", threshold) # we want to write this to <root>/root.cfg path = root + pathsep + "root.cfg" f = open(path, "w") cp.write(f) f.close() return path
def get_config(): if sys.platform == 'win32': config_path = 'Racer.ini' else: config_path = 'racer.cfg' config = ConfigParser() if os.path.exists(config_path): config.read(config_path) else: config.add_section("tree") config.set("tree", "type", "pro400") config.set("tree", "auto_reset", "0") config.set("tree", "zero_perfect", False) config.set("tree", "autostart_min", 1.0) config.set("tree", "autostart_max", 3.0) config.add_section("player") config.set("player", "left_lane", "computer") config.set("player", "right_lane", "human") config.set("player", "left_rollout", 0.220) config.set("player", "right_rollout", 0.220) config.add_section("display") config.set("display", "fullscreen", False) config.set("display", "resolution", "480x700") config.set("display", "hardware_accel", False) config.set("display", "double_buffering", False) config.add_section("computer") config.set("computer", "reaction_min", -0.009) config.set("computer", "reaction_max", 0.115) with open(config_path, "wb") as config_file: config.write(config_file) return config
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)
def buttonExportSensors_clicked_cb(self, widget): treemodel, treeiter = self.treeviewSensors.get_selection().get_selected() if treeiter: sensorNumber = int(treemodel.get_path(treeiter)[0]) dialog = gtk.FileChooserDialog("Salvar..", None, gtk.FILE_CHOOSER_ACTION_SAVE, (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_SAVE, gtk.RESPONSE_OK)) dialog.set_default_response(gtk.RESPONSE_OK) dialog.set_current_folder(dialog.get_current_folder() + "/sensors/") dialog.set_current_name(self.sensorTypes[sensorNumber].name + ".sensor") response = dialog.run() if response == gtk.RESPONSE_OK: filename = dialog.get_filename() FILE = open(filename, "w") c = ConfigParser() for i in range(len(self.sensorTypes[sensorNumber].points) - 1, -1, -1): c.add_section("POINT " + str(i)) c.set("POINT " + str(i), "x", self.sensorTypes[sensorNumber].points[i][0]) c.set("POINT " + str(i), "y", self.sensorTypes[sensorNumber].points[i][1]) c.add_section("SENSOR") c.set("SENSOR", "name", self.sensorTypes[sensorNumber].name) c.set("SENSOR", "unit", self.sensorTypes[sensorNumber].unit) c.set("SENSOR", "description", self.sensorTypes[sensorNumber].description) c.write(FILE) FILE.close() dialog.destroy()
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 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 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 _load_config(self): config_file = os.path.expanduser(self.filename) self.log.debug("Enter _load_config(%s)" % config_file) config = ConfigParser() Configuration.changed_settings = False # track changes config.read(config_file) if config.has_section('settings'): if config.has_option('settings', 'destination'): self.set_destination(config.get('settings', 'destination')) if config.has_option('settings', 'date_pattern'): self.date_pattern = config.get('settings', 'date_pattern', True) if config.has_option('settings', 'tempdir'): self.tempdir = os.path.abspath(os.path.expanduser(config.get('settings', 'tempdir'))) if not os.path.exists(self.tempdir): os.makedirs(self.tempdir) if config.has_option('settings', 'comment_pattern'): pattern = config.get('settings', 'comment_pattern', True) pattern = re.sub(r'%([a-z_][a-z_]+)', r'%(\1)s', pattern) self.comment_pattern = pattern self._read_feed_settings(config) self._add_stations(config) if Configuration.changed_settings: import shutil shutil.copy(config_file, config_file + '.bak') with open(config_file, 'w') as file: config.write(file) print("WARNING: Saved the old version of config file as '%s.bak' and updated configuration." % (config_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 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()
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 write(self): with open(pymt_config_fn, 'w') as fd: ConfigParser.write(self, fd)
class Config(object): """ Provide read and write access to application configuration settings. Built as a wrapper around ConfigParser: Properties exist to read and write values but ConfigParser does the actual reading and writing of the configuration file. """ def __init__(self, path): self.path = path self._set_default_fonts() self.config_parser = ConfigParser(DEFAULTS) def read(self): """Read settings from file specified in constructor.""" self.config_parser.read(self.path) def write(self): """ Write settings to file specified in constructor and raise IOError if failed. """ f = open(self.path, "w") try: self.config_parser.write(f) finally: f.close() def get_selected_event_box_drawer(self): return self.config_parser.get( DEFAULTSECT, SELECTED_EVENT_BOX_DRAWER).decode("utf-8") def set_selected_event_box_drawer(self, selected): self.config_parser.set(DEFAULTSECT, SELECTED_EVENT_BOX_DRAWER, str(selected.encode("utf-8"))) selected_event_box_drawer = property(get_selected_event_box_drawer, set_selected_event_box_drawer) def get_window_size(self): return (self.config_parser.getint(DEFAULTSECT, WINDOW_WIDTH), self.config_parser.getint(DEFAULTSECT, WINDOW_HEIGHT)) def set_window_size(self, size): width, height = size self.config_parser.set(DEFAULTSECT, WINDOW_WIDTH, str(width)) self.config_parser.set(DEFAULTSECT, WINDOW_HEIGHT, str(height)) window_size = property(get_window_size, set_window_size) def get_window_pos(self): width, _ = self.get_window_size() # Make sure that some area of the window is visible on the screen # Some part of the titlebar must be visible xpos = max(-width + 100, self.config_parser.getint(DEFAULTSECT, WINDOW_XPOS)) # Titlebar must not be above the upper screen border ypos = max(0, self.config_parser.getint(DEFAULTSECT, WINDOW_YPOS)) return (xpos, ypos) def set_window_pos(self, pos): xpos, ypos = pos self.config_parser.set(DEFAULTSECT, WINDOW_XPOS, str(xpos)) self.config_parser.set(DEFAULTSECT, WINDOW_YPOS, str(ypos)) window_pos = property(get_window_pos, set_window_pos) def get_window_maximized(self): return self.config_parser.getboolean(DEFAULTSECT, WINDOW_MAXIMIZED) def set_window_maximized(self, maximized): self.config_parser.set(DEFAULTSECT, WINDOW_MAXIMIZED, str(maximized)) window_maximized = property(get_window_maximized, set_window_maximized) def get_show_sidebar(self): return self.config_parser.getboolean(DEFAULTSECT, SHOW_SIDEBAR) def set_show_sidebar(self, show): self.config_parser.set(DEFAULTSECT, SHOW_SIDEBAR, str(show)) show_sidebar = property(get_show_sidebar, set_show_sidebar) def get_show_legend(self): return self.config_parser.getboolean(DEFAULTSECT, SHOW_LEGEND) def set_show_legend(self, show): self.config_parser.set(DEFAULTSECT, SHOW_LEGEND, str(show)) show_legend = property(get_show_legend, set_show_legend) def get_sidebar_width(self): return self.config_parser.getint(DEFAULTSECT, SIDEBAR_WIDTH) def set_sidebar_width(self, width): self.config_parser.set(DEFAULTSECT, SIDEBAR_WIDTH, str(width)) sidebar_width = property(get_sidebar_width, set_sidebar_width) def get_divider_line_slider_pos(self): return self.config_parser.getint(DEFAULTSECT, DIVIDER_LINE_SLIDER_POS) def set_divider_line_slider_pos(self, pos): self.config_parser.set(DEFAULTSECT, DIVIDER_LINE_SLIDER_POS, str(pos)) divider_line_slider_pos = property(get_divider_line_slider_pos, set_divider_line_slider_pos) def get_recently_opened(self): ro = self.config_parser.get(DEFAULTSECT, RECENT_FILES).decode(ENCODING).split(",") # Filter out empty elements: "".split(",") will return [""] but we want # the empty list ro_filtered = [x for x in ro if x] return ro_filtered recently_opened = property(get_recently_opened) def has_recently_opened_files(self): if not self.get_open_recent_at_startup(): return False else: return len(self.recently_opened) > 0 def get_latest_recently_opened_file(self): return self.recently_opened[0] def append_recently_opened(self, path): if path in [":tutorial:"]: # Special timelines should not be saved return if isinstance(path, str): # This path might have come from the command line so we need to convert # it to unicode path = path.decode(sys.getfilesystemencoding()) abs_path = os.path.abspath(path) current = self.recently_opened # Just keep one entry of the same path in the list if abs_path in current: current.remove(abs_path) current.insert(0, abs_path) self.config_parser.set(DEFAULTSECT, RECENT_FILES, (",".join( current[:MAX_NBR_OF_RECENT_FILES_SAVED])).encode(ENCODING)) def get_open_recent_at_startup(self): return self.config_parser.getboolean(DEFAULTSECT, OPEN_RECENT_AT_STARTUP) def set_open_recent_at_startup(self, value): self.config_parser.set(DEFAULTSECT, OPEN_RECENT_AT_STARTUP, str(value)) open_recent_at_startup = property(get_open_recent_at_startup, set_open_recent_at_startup) def get_balloon_on_hover(self): return self.config_parser.getboolean(DEFAULTSECT, BALLOON_ON_HOVER) def set_balloon_on_hover(self, balloon_on_hover): self.config_parser.set(DEFAULTSECT, BALLOON_ON_HOVER, str(balloon_on_hover)) balloon_on_hover = property(get_balloon_on_hover, set_balloon_on_hover) def get_week_start(self): return self.config_parser.get(DEFAULTSECT, WEEK_START) def set_week_start(self, week_start): if week_start not in ["monday", "sunday"]: raise ValueError("Invalid week start.") self.config_parser.set(DEFAULTSECT, WEEK_START, week_start) week_start = property(get_week_start, set_week_start) def get_use_inertial_scrolling(self): return self.config_parser.getboolean(DEFAULTSECT, USE_INERTIAL_SCROLLING) def set_use_inertial_scrolling(self, value): self.config_parser.set(DEFAULTSECT, USE_INERTIAL_SCROLLING, str(value)) use_inertial_scrolling = property(get_use_inertial_scrolling, set_use_inertial_scrolling) def get_shortcut_key(self, cfgid, default): try: return self.config_parser.get(DEFAULTSECT, cfgid) except: self.set_shortcut_key(cfgid, default) return default def set_shortcut_key(self, cfgid, value): self.config_parser.set(DEFAULTSECT, cfgid, value) def get_experimental_features(self): return self.config_parser.get(DEFAULTSECT, EXPERIMENTAL_FEATURES) def set_experimental_features(self, value): self.config_parser.set(DEFAULTSECT, EXPERIMENTAL_FEATURES, value) experimental_features = property(get_experimental_features, set_experimental_features) def get_never_show_period_events_as_point_events(self): return self.config_parser.getboolean( DEFAULTSECT, NEVER_SHOW_PERIOD_EVENTS_AS_POINT_EVENTS) def set_never_show_period_events_as_point_events(self, value): self.config_parser.set(DEFAULTSECT, NEVER_SHOW_PERIOD_EVENTS_AS_POINT_EVENTS, str(value)) never_show_period_events_as_point_events = property( get_never_show_period_events_as_point_events, set_never_show_period_events_as_point_events) def get_center_event_texts(self): return self.config_parser.getboolean(DEFAULTSECT, CENTER_EVENT_TEXTS) def set_center_event_texts(self, value): self.config_parser.set(DEFAULTSECT, CENTER_EVENT_TEXTS, str(value)) center_event_texts = property(get_center_event_texts, set_center_event_texts) def get_draw_period_events_to_right(self): return self.config_parser.getboolean(DEFAULTSECT, DRAW_POINT_EVENTS_TO_RIGHT) def set_draw_period_events_to_right(self, value): self.config_parser.set(DEFAULTSECT, DRAW_POINT_EVENTS_TO_RIGHT, str(value)) draw_period_events_to_right = property(get_draw_period_events_to_right, set_draw_period_events_to_right) def get_major_strip_font(self): return self.config_parser.get(DEFAULTSECT, MAJOR_STRIP_FONT) def set_major_strip_font(self, font): self.config_parser.set(DEFAULTSECT, MAJOR_STRIP_FONT, font) major_strip_font = property(get_major_strip_font, set_major_strip_font) def get_minor_strip_font(self): return self.config_parser.get(DEFAULTSECT, MINOR_STRIP_FONT) def set_minor_strip_font(self, font): self.config_parser.set(DEFAULTSECT, MINOR_STRIP_FONT, font) minor_strip_font = property(get_minor_strip_font, set_minor_strip_font) def get_legend_font(self): return self.config_parser.get(DEFAULTSECT, LEGEND_FONT) def set_legend_font(self, font): self.config_parser.set(DEFAULTSECT, LEGEND_FONT, font) legend_font = property(get_legend_font, set_legend_font) def _set_default_fonts(self): DEFAULTS[MAJOR_STRIP_FONT] = Font( 12, weight=wx.FONTWEIGHT_BOLD).serialize() DEFAULTS[MINOR_STRIP_FONT] = Font(8).serialize() DEFAULTS[LEGEND_FONT] = Font(8).serialize() def get_event_editor_show_period(self): return self.config_parser.getboolean(DEFAULTSECT, EVENT_EDITOR_SHOW_PERIOD) def set_event_editor_show_period(self, value): self.config_parser.set(DEFAULTSECT, EVENT_EDITOR_SHOW_PERIOD, str(value)) event_editor_show_period = property(get_event_editor_show_period, set_event_editor_show_period) def get_event_editor_show_time(self): return self.config_parser.getboolean(DEFAULTSECT, EVENT_EDITOR_SHOW_TIME) def set_event_editor_show_time(self, value): self.config_parser.set(DEFAULTSECT, EVENT_EDITOR_SHOW_TIME, str(value)) event_editor_show_time = property(get_event_editor_show_time, set_event_editor_show_time) def get_event_editor_tab_order(self): return self.config_parser.get(DEFAULTSECT, EVENT_EDITOR_TAB_ORDER) def set_event_editor_tab_order(self, tab_order): self.config_parser.set(DEFAULTSECT, EVENT_EDITOR_TAB_ORDER, tab_order) event_editor_tab_order = property(get_event_editor_tab_order, set_event_editor_tab_order)
def save_config_scenario(type): if len(save_scenario_dic) > 0: display_save_scenario(save_scenario_dic, type) save_check = select_yesno_menu('Do you want to save the above information?(y/n) : ') if 'y' == save_check: while 1: scen_name = raw_input(RED +'Input Save File Name : '+ENDC) scen_file = SCENARIO_PATH + type + '_' + scen_name + '.ini' dup_check = scenario_file_duplicate_check(type + '_' + scen_name) if True is dup_check: Reporter.PRINTR(" The file name exists. Please enter again!") continue else: break dic = save_scenario_dic scen_ini = ConfigParser() # Network net_item = dic.get('network') if None is not net_item: scen_ini.add_section('network') for i in range(len(net_item)): set_str = 'set' + str(i+1) scen_ini.set('network', set_str, net_item[i]) # Subnet sub_item = dic.get('subnet') if None is not sub_item: scen_ini.add_section('subnet') for i in range(len(sub_item)): set_str = 'set' + str(i+1) scen_ini.set('subnet', set_str, sub_item[i]) # Router router_item = dic.get('router') if None is not router_item: scen_ini.add_section('router') for i in range(len(router_item)): set_str = 'set' + str(i+1) scen_ini.set('router', set_str, router_item[i]) # Router Interface router_if_item = dic.get('router-interface') if None is not router_if_item: scen_ini.add_section('router-interface') for i in range(len(router_if_item)): set_str = 'set' + str(i+1) scen_ini.set('router-interface', set_str, router_if_item[i]) # Security_group sg_item = dic.get('security_group') if None is not sg_item: scen_ini.add_section('security_group') for i in range(len(sg_item)): set_str = 'set' + str(i+1) scen_ini.set('security_group', set_str, sg_item[i]) # Instance inst_item = dic.get('instance') if None is not inst_item: scen_ini.add_section('instance') for i in range(len(inst_item)): set_str = 'set' + str(i+1) scen_ini.set('instance', set_str, inst_item[i]) # Floating Ip associate fip_as_item = dic.get('floatingip_associate') if None is not fip_as_item: scen_ini.add_section('floatingip_associate') for i in range(len(fip_as_item)): set_str = 'set_' + str(i+1) scen_ini.set('floatingip_associate', set_str, fip_as_item[i]) wlen = 0 with open(scen_file, 'w') as configfile: wlen = scen_ini.write(configfile) Reporter.PRINTR(" Success %s save file !", scen_file) else: Reporter.PRINTR(" => Storing information does not exist.")
# Configuration, primarily database connection string. # ---------------------------------------------------------------------------- if opts.prod: config_in.read('g2e/config/prod.ini') config_out.set('mode', 'debug', False) else: config_in.read('g2e/config/dev.ini') config_out.set('mode', 'debug', True) config_out.set('admin', 'admin_key', config_in.get('admin', 'admin_key')) config_out.set('db', 'uri', config_in.get('db', 'uri')) config_out.set('cookies', 'secret_key', config_in.get('cookies', 'secret_key')) with open('g2e/config/config.ini', 'wb') as configfile: config_out.write(configfile) subprocess.call('docker-machine start default', shell=True) subprocess.call('eval "$(docker-machine env default)"', shell=True) if opts.build and not opts.nocache: subprocess.call('docker build -t %s .' % opts.image, shell=True) elif opts.build and opts.nocache: subprocess.call('docker build --no-cache -t %s .' % opts.image, shell=True) # Reset DB credentials so we can keep developing locally. # ---------------------------------------------------------------------------- config_in = ConfigParser() config_in.read('g2e/config/dev.ini') config_out = ConfigParser()
def strava_upload(): """ upload to strava, borrowed from https://github.com/dlenski/stravacli """ allowed_exts = { '.tcx': lambda v: '<TrainingCenterDatabase' in v[:200], '.gpx': lambda v: '<gpx' in v[:200], '.fit': lambda v: v[8:12] == '.FIT' } par = argparse.ArgumentParser(description='Uploads activities to Strava.') par.add_argument( 'activities', nargs='*', type=argparse.FileType("rb"), default=(stdin, ), help="Activity files to upload (plain or gzipped {})".format(', '.join(allowed_exts))) par.add_argument( '-P', '--no-popup', action='store_true', help="Don't browse to activities after upload.") par.add_argument( '-E', '--env', help='Look for ACCESS_TOKEN in environment variable ' 'rather than ~/.stravacli') grp = par.add_argument_group('Activity file details') grp.add_argument('-p', '--private', action='store_true', help='Make activities private') grp.add_argument( '-t', '--type', choices=allowed_exts, default=None, help='Force files to be interpreted as being of given ' 'type (default is to autodetect based on name, or ' 'contents for stdin)') grp.add_argument( '-x', '--xml-desc', action='store_true', help='Parse name/description fields from GPX and TCX ' 'files.') grp.add_argument('-T', '--title', help='Activity title') grp.add_argument('-D', '--desc', dest='description', help='Activity description') grp.add_argument( '-A', '--activity-type', default=None, help='Type of activity. If not specified, the default ' 'value is taken from user profile. ' 'Supported values: \n\t ride, run, swim, workout, ' 'hike, walk, nordicski, alpineski, backcountryski, ' 'iceskate, inlineskate, kitesurf, rollerski, ' 'windsurf, workout, snowboard, snowshoe') args = par.parse_args() if args.xml_desc: if args.title: print('argument -T/--title not allowed with argument ' '-x/--xml-desc', file=stderr) if args.description: print('argument -D/--desc not allowed with argument ' '-x/--xml-desc', file=stderr) # Authorize Strava cp_ = ConfigParser() cp_.read(os.path.expanduser('~/.stravacli')) cat = None if cp_.has_section('API'): if 'access_token' in cp_.options('API'): cat = cp_.get('API', 'ACCESS_TOKEN') cs = cp_.get('API', 'CLIENT_SECRET') cat = cp_.get('API', 'ACCESS_TOKEN') while True: client = Client(cat) try: athlete = client.get_athlete() except requests.exceptions.ConnectionError: print("Could not connect to Strava API", file=stderr) except Exception as e: print("NOT AUTHORIZED %s" % e, file=stderr) print( "Need Strava API access token. Launching web browser to " "obtain one.", file=stderr) client = Client() webserver = QueryGrabber(response='<title>Strava auth code received!</title>This window can be closed.') _scope = 'view_private,write' authorize_url = client.authorization_url(client_id=cid, redirect_uri=webserver.root_uri(), scope=_scope) webbrowser.open_new_tab(authorize_url) webserver.handle_request() client.access_token = cat = client.exchange_code_for_token(client_id=cid,client_secret=cs,code=webserver.received['code']) cp_.add_section('API') cp_.set('API','CLIENT_ID', cid) cp_.set('API','CLIENT_SECRET', cs) cp_.set('API','ACCESS_TOKEN', cat) cp_.write(open(os.path.expanduser('~/.stravacli'),"w")) else: if not cp_.has_section('API'): cp_.add_section('API') if 'ACCESS_TOKEN' not in cp_.options('API') or cp_.get('API', 'ACCESS_TOKEN', None) != cat: cp_.set('API', 'ACCESS_TOKEN', cat) cp_.write(open(os.path.expanduser('~/.stravacli'), "w")) break print("Authorized to access account of {} {} (id {:d}).".format(athlete.firstname, athlete.lastname, athlete.id)) for act in args.activities: if act is stdin: contents = act.read() act = StringIO(contents) if args.type is None: # autodetect gzip and extension based on content if contents.startswith('\x1f\x8b'): gz_, cf_, uf_ = '.gz', act, gzip.GzipFile(fileobj=act, mode='rb') contents = uf_.read() else: gz_, uf_, cf_ = '', act, NamedTemporaryFile(suffix='.gz') gzip.GzipFile(fileobj=cf_, mode='w+b').writelines(act) for ext, checker in allowed_exts.items(): if checker(contents): print("Uploading {} activity from stdin...".format(ext + gz_)) break else: print("Could not determine file type of stdin", file=stderr) else: base, ext = 'activity', args.type else: base, ext = os.path.splitext(act.name if args.type is None else 'activity.' + args.type) # autodetect based on extensions if ext.lower() == '.gz': base, ext = os.path.splitext(base) # un-gzip it in order to parse it gz_, cf_, uf_ = '.gz', act, None if args.no_parse else \ gzip.GzipFile(fileobj=act, mode='rb') else: gz_, uf_, cf_ = '', act, NamedTemporaryFile(suffix='.gz') gzip.GzipFile(fileobj=cf_, mode='w+b').writelines(act) if ext.lower() not in allowed_exts: print( "Don't know how to handle extension " "{} (allowed are {}).".format(ext, ', '.join(allowed_exts)), file=stderr) print("Uploading {} activity from {}...".format(ext + gz_, act.name)) # try to parse activity name, description from file if requested if args.xml_desc: uf_.seek(0, 0) if ext.lower() == '.gpx': x = etree.parse(uf_) nametag, desctag = x.find("{*}name"), x.find("{*}desc") title = nametag and nametag.text desc = desctag and desctag.text elif ext.lower() == '.tcx': x = etree.parse(uf_) notestag = x.find("{*}Activities/{*}Activity/{*}Notes") if notestag is not None: title, desc = (notestag.text.split('\n', 1) + [None])[:2] else: title = args.title desc = args.description # upload activity try: cf_.seek(0, 0) upstat = client.upload_activity( cf_, ext[1:] + '.gz', title, desc, private=args.private, activity_type=args.activity_type) activity = upstat.wait() duplicate = False except exc.ActivityUploadFailed as e: words = e.args[0].split() if words[-4:-1] == ['duplicate', 'of', 'activity']: activity = client.get_activity(words[-1]) duplicate = True else: raise # show results uri = "http://strava.com/activities/{:d}".format(activity.id) print(" {}{}".format(uri, " (duplicate)" if duplicate else ''), file=stderr) if not args.no_popup: webbrowser.open_new_tab(uri)
def downloadReadingList(list, orig_config, callback, use_cache=True, re_read=True): from planet import logger import config try: import urllib2, StringIO from planet.spider import filename # list cache file name cache_filename = filename(config.cache_lists_directory(), list) # retrieve list options (e.g., etag, last-modified) from cache options = {} # add original options for key in orig_config.options(list): options[key] = orig_config.get(list, key) try: if use_cache: cached_config = ConfigParser() cached_config.read(cache_filename) for option in cached_config.options(list): options[option] = cached_config.get(list, option) except: pass cached_config = ConfigParser() cached_config.add_section(list) for key, value in options.items(): cached_config.set(list, key, value) # read list curdir = getattr(os.path, 'curdir', '.') if sys.platform.find('win') < 0: base = urljoin('file:', os.path.abspath(curdir)) else: path = os.path.abspath(os.path.curdir) base = urljoin('file:///', path.replace(':', '|').replace('\\', '/')) request = urllib2.Request(urljoin(base + '/', list)) if options.has_key("etag"): request.add_header('If-None-Match', options['etag']) if options.has_key("last-modified"): request.add_header('If-Modified-Since', options['last-modified']) response = urllib2.urlopen(request) if response.headers.has_key('etag'): cached_config.set(list, 'etag', response.headers['etag']) if response.headers.has_key('last-modified'): cached_config.set(list, 'last-modified', response.headers['last-modified']) # convert to config.ini data = StringIO.StringIO(response.read()) if callback: callback(data, cached_config) # write to cache if use_cache: cache = open(cache_filename, 'w') cached_config.write(cache) cache.close() # re-parse and proceed logger.debug("Using %s readinglist", list) if re_read: if use_cache: orig_config.read(cache_filename) else: cdata = StringIO.StringIO() cached_config.write(cdata) cdata.seek(0) orig_config.readfp(cdata) except: try: if re_read: if use_cache: if not orig_config.read(cache_filename): raise Exception() else: cdata = StringIO.StringIO() cached_config.write(cdata) cdata.seek(0) orig_config.readfp(cdata) logger.info("Using cached %s readinglist", list) except: logger.exception("Unable to read %s readinglist", list)
txtOutPaths.append(application.getTxtOutPath()) if generateTSV: from PyPop.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'))
class LibraryInfo(object): def __init__(self, libraryName, infoFileName): self.libraryName = libraryName self.fileName = infoFileName self.info = ConfigParser() self.songCount = 0 try: self.info.read(infoFileName) except: pass # Set a default name if not self.name: self.name = os.path.basename(os.path.dirname(self.fileName)) # Count the available songs libraryRoot = os.path.dirname(self.fileName) for name in os.listdir(libraryRoot): if not os.path.isdir(os.path.join(libraryRoot, name)) or name.startswith("."): continue if os.path.isfile(os.path.join(libraryRoot, name, "song.ini")): self.songCount += 1 def _set(self, attr, value): if not self.info.has_section("library"): self.info.add_section("library") if type(value) == unicode: value = value.encode(Config.encoding) else: value = str(value) self.info.set("library", attr, value) def save(self): f = open(self.fileName, "w") self.info.write(f) f.close() def _get(self, attr, type=None, default=""): try: v = self.info.get("library", attr) except: v = default if v is not None and type: v = type(v) return v def getName(self): return self._get("name") def setName(self, value): self._set("name", value) def getColor(self): c = self._get("color") if c: return Theme.hexToColor(c) def setColor(self, color): self._set("color", Theme.colorToHex(color)) name = property(getName, setName) color = property(getColor, setColor)
class Mixer(Gtk.Window): """ Volti Mixer Application""" def __init__(self): GObject.GObject.__init__(self) self.cp = ConfigParser() self.cp.read(CONFIG_FILE) self.lock_mask = {} self.control_mask = {} self.card_hbox = {} self.alsa_channels = {} self.set_title("Volti Mixer") self.set_resizable(True) self.set_border_width(5) self.set_position(Gtk.WindowPosition.CENTER) self.add_events(Gdk.EventMask.BUTTON_PRESS_MASK) self.connect('delete_event', self.quit) icon_theme = Gtk.IconTheme.get_default() if icon_theme.has_icon("multimedia-volume-control"): self.set_icon_name("multimedia-volume-control") else: file = os.path.join(RES_DIR, "icons", "multimedia-volume-control.svg") self.set_icon_from_file(file) self.acards = alsa.cards() self.set_layout() self.init_controls() self.show() card_index = int(self.cp.get("global", "card_index")) self.notebook.set_current_page(card_index) def set_layout(self): """ Gui layout """ self.notebook = Gtk.Notebook() self.notebook.set_tab_pos(Gtk.PositionType.TOP) self.notebook.show() vbox = Gtk.VBox() vbox.add(self.notebook) self.add(vbox) bbox = Gtk.HButtonBox() bbox.set_layout(Gtk.ButtonBoxStyle.EDGE) button1 = Gtk.Button(label=_('_Select Controls...')) button1.connect("clicked", self.on_select_controls) bbox.add(button1) button2 = Gtk.Button(stock=Gtk.STOCK_QUIT) button2.connect("clicked", self.quit) bbox.add(button2) align = Gtk.Alignment.new(xscale=1, yscale=1) align.set_padding(5, 0, 0, 0) align.add(bbox) vbox.pack_start(align, False, False) vbox.show_all() def init_controls(self): try: show_values = bool(int(self.cp.get("global", "mixer_show_values"))) except: show_values = False for card_index, card_name in enumerate(self.acards): vbox = Gtk.VBox() frame = Gtk.Frame() hbox = Gtk.HBox(True, 10) align = Gtk.Alignment.new(xscale=1, yscale=1) align.set_padding(10, 10, 10, 10) align.add(hbox) vbox.add(align) frame.add(vbox) self.card_hbox[card_index] = hbox self.notebook.insert_page(frame, Gtk.Label(label=card_name), card_index) try: self.lock_mask[card_index] = int( self.cp.get("card-%d" % card_index, "mask_lock")) except: self.lock_mask[card_index] = 0 try: self.control_mask[card_index] = int( self.cp.get("card-%d" % card_index, "mask_control")) except: self.control_mask[card_index] = 0 amixers = [] try: amixers = alsa.mixers(card_index) except alsa.ALSAAudioError: pass for count, mixer in enumerate(amixers): self.control_mask[card_index] |= (1 << count) n = 0 self.get_channels(card_index) for channel, id in self.alsa_channels[card_index]: option_mask = option_value = _LOCK mixer = alsa.Mixer(channel, id, card_index) if not len(mixer.volumecap()): continue if len(mixer.getvolume()) > 1: option_mask |= _STEREO option_mask |= _LOCK if self.lock_mask[card_index] & (1 << n): option_value |= _LOCK try: if mixer.getrec(): option_mask |= _REC if mixer.getrec()[0]: option_value |= _REC if mixer.getmute(): option_mask |= _MUTE if mixer.getmute()[0]: option_value |= _MUTE except: pass for el in hbox, align, vbox, frame: el.show() volume = MixerControl(n, option_mask, option_value, show_values, card_index, channel) volume.set_level(self.get_volume(n, card_index)) volume.connect("volume_changed", self.adjust_volume) volume.connect("volume_setting_toggled", self.setting_toggled) hbox.pack_start(volume, True, True) n += 1 self.show_hide_controls(card_index) def get_channels(self, card_index): try: self.alsa_channels[card_index] = [] for channel in alsa.mixers(card_index): id = 0 while (channel, id) in self.alsa_channels[card_index]: id += 1 mixer = alsa.Mixer(channel, id, card_index) if len(mixer.volumecap()): self.alsa_channels[card_index].append((channel, id)) except: pass def setting_toggled(self, vol, channel, button, val, card_index): """ Handle checkbox toggles """ ch, id = self.alsa_channels[card_index][channel] mixer = alsa.Mixer(ch, id, card_index) if button == _MUTE: mixer.setmute(val) if button == _LOCK: if val: self.lock_mask[card_index] |= (1 << channel) else: self.lock_mask[card_index] &= ~(1 << channel) if button == _REC: mixer.setrec(val) def adjust_volume(self, vol, channel, volume1, volume2, card_index): """ Track changes to the volume controls """ self.set_volume((volume1, volume2), channel, card_index) def set_volume(self, volume, channel, card_index): """ Set the playback volume """ ch, id = self.alsa_channels[card_index][channel] mixer = alsa.Mixer(ch, id, card_index) try: mixer.setvolume(volume[0], 0) mixer.setvolume(volume[1], 1) except: pass def get_volume(self, channel, card_index): """ Get the current sound card setting for specified channel """ ch, id = self.alsa_channels[card_index][channel] mixer = alsa.Mixer(ch, id, card_index) vol = mixer.getvolume() if len(vol) == 1: return (vol[0], vol[0]) return (vol[0], vol[1]) def on_select_controls(self, widget=None): card_index = self.notebook.get_current_page() dialog = SelectControls(self, self.cp, card_index) def show_hide_controls(self, card_index): controls = self.card_hbox[card_index].get_children() for control in controls: if self.control_mask[card_index] & (1 << control.channel): control.show() else: control.hide() def write_config(self): for card_index, card_name in enumerate(self.acards): section = "card-%d" % card_index if not self.cp.has_section(section): self.cp.add_section(section) self.cp.set(section, "mask_lock", self.lock_mask[card_index]) self.cp.write(open(CONFIG_FILE, "w")) def quit(self, element=None, event=None): """ Exit main loop """ self.write_config() Gtk.main_quit()
class SongInfo(object): def __init__(self, infoFileName): self.songName = os.path.basename(os.path.dirname(infoFileName)) self.fileName = infoFileName self.info = ConfigParser() self._difficulties = None try: self.info.read(infoFileName) except: pass # Read highscores and verify their hashes. # There ain't no security like security throught obscurity :) self.highScores = {} scores = self._get("scores", str, "") if scores: scores = Cerealizer.loads(binascii.unhexlify(scores)) for difficulty in scores.keys(): try: difficulty = difficulties[difficulty] except KeyError: continue for score, stars, name, hash in scores[difficulty.id]: if self.getScoreHash(difficulty, score, stars, name) == hash: self.addHighscore(difficulty, score, stars, name) else: Log.warn( "Weak hack attempt detected. Better luck next time." ) def _set(self, attr, value): if not self.info.has_section("song"): self.info.add_section("song") if type(value) == unicode: value = value.encode(Config.encoding) else: value = str(value) self.info.set("song", attr, value) def getObfuscatedScores(self): s = {} for difficulty in self.highScores.keys(): s[difficulty.id] = [ (score, stars, name, self.getScoreHash(difficulty, score, stars, name)) for score, stars, name in self.highScores[difficulty] ] return binascii.hexlify(Cerealizer.dumps(s)) def save(self): self._set("scores", self.getObfuscatedScores()) f = open(self.fileName, "w") self.info.write(f) f.close() def _get(self, attr, type=None, default=""): try: v = self.info.get("song", attr) except: v = default if v is not None and type: v = type(v) return v def getDifficulties(self): # Tutorials only have the medium difficulty if self.tutorial: return [difficulties[MEDIUM_DIFFICULTY]] if self._difficulties is not None: return self._difficulties # See which difficulties are available try: noteFileName = os.path.join(os.path.dirname(self.fileName), "notes.mid") info = MidiInfoReader() midiIn = midi.MidiInFile(info, noteFileName) try: midiIn.read() except MidiInfoReader.Done: pass info.difficulties.sort(lambda a, b: cmp(b.id, a.id)) self._difficulties = info.difficulties except: self._difficulties = difficulties.values() return self._difficulties def getName(self): return self._get("name") def setName(self, value): self._set("name", value) def getArtist(self): return self._get("artist") def getCassetteColor(self): c = self._get("cassettecolor") if c: return Theme.hexToColor(c) def setCassetteColor(self, color): self._set("cassettecolor", Theme.colorToHex(color)) def setArtist(self, value): self._set("artist", value) def getScoreHash(self, difficulty, score, stars, name): return sha.sha("%d%d%d%s" % (difficulty.id, score, stars, name)).hexdigest() def getDelay(self): return self._get("delay", int, 0) def setDelay(self, value): return self._set("delay", value) def getHighscores(self, difficulty): try: return self.highScores[difficulty] except KeyError: return [] def uploadHighscores(self, url, songHash): try: d = { "songName": self.songName, "songHash": songHash, "scores": self.getObfuscatedScores(), "version": Version.version() } data = urllib.urlopen(url + "?" + urllib.urlencode(d)).read() Log.debug("Score upload result: %s" % data) if ";" in data: fields = data.split(";") else: fields = [data, "0"] return (fields[0] == "True", int(fields[1])) except Exception, e: Log.error(e) return (False, 0)
class Config(object): """ Provide read and write access to application configuration settings. Built as a wrapper around ConfigParser: Properties exist to read and write values but ConfigParser does the actual reading and writing of the configuration file. """ def __init__(self, path): self.path = path self.config_parser = ConfigParser(DEFAULTS) def read(self): """Read settings from file specified in constructor.""" self.config_parser.read(self.path) def write(self): """ Write settings to file specified in constructor and raise IOError if failed. """ f = open(self.path, "w") try: self.config_parser.write(f) finally: f.close() def get_window_size(self): return (self.config_parser.getint(DEFAULTSECT, WINDOW_WIDTH), self.config_parser.getint(DEFAULTSECT, WINDOW_HEIGHT)) def set_window_size(self, size): width, height = size self.config_parser.set(DEFAULTSECT, WINDOW_WIDTH, str(width)) self.config_parser.set(DEFAULTSECT, WINDOW_HEIGHT, str(height)) window_size = property(get_window_size, set_window_size) def get_window_pos(self): width, height = self.get_window_size() # Make sure that some area of the window is visible on the screen # Some part of the titlebar must be visible xpos = max(-width + 100, self.config_parser.getint(DEFAULTSECT, WINDOW_XPOS)) # Titlebar must not be above the upper screen border ypos = max(0, self.config_parser.getint(DEFAULTSECT, WINDOW_YPOS)) return (xpos, ypos) def set_window_pos(self, pos): xpos, ypos = pos self.config_parser.set(DEFAULTSECT, WINDOW_XPOS, str(xpos)) self.config_parser.set(DEFAULTSECT, WINDOW_YPOS, str(ypos)) window_pos = property(get_window_pos, set_window_pos) def get_window_maximized(self): return self.config_parser.getboolean(DEFAULTSECT, WINDOW_MAXIMIZED) def set_window_maximized(self, maximized): self.config_parser.set(DEFAULTSECT, WINDOW_MAXIMIZED, str(maximized)) window_maximized = property(get_window_maximized, set_window_maximized) def get_show_sidebar(self): return self.config_parser.getboolean(DEFAULTSECT, SHOW_SIDEBAR) def set_show_sidebar(self, show): self.config_parser.set(DEFAULTSECT, SHOW_SIDEBAR, str(show)) show_sidebar = property(get_show_sidebar, set_show_sidebar) def get_show_legend(self): return self.config_parser.getboolean(DEFAULTSECT, SHOW_LEGEND) def set_show_legend(self, show): self.config_parser.set(DEFAULTSECT, SHOW_LEGEND, str(show)) show_legend = property(get_show_legend, set_show_legend) def get_sidebar_width(self): return self.config_parser.getint(DEFAULTSECT, SIDEBAR_WIDTH) def set_sidebar_width(self, width): self.config_parser.set(DEFAULTSECT, SIDEBAR_WIDTH, str(width)) sidebar_width = property(get_sidebar_width, set_sidebar_width) def get_recently_opened(self): ro = self.config_parser.get(DEFAULTSECT, RECENT_FILES).decode(ENCODING).split(",") # Filter out empty elements: "".split(",") will return [""] but we want # the empty list ro_filtered = [x for x in ro if x] return ro_filtered recently_opened = property(get_recently_opened) def append_recently_opened(self, path): if path in [":tutorial:"]: # Special timelines should not be saved return if isinstance(path, str): # This path might have come from the command line so we need to convert # it to unicode path = path.decode(sys.getfilesystemencoding()) abs_path = os.path.abspath(path) current = self.recently_opened # Just keep one entry of the same path in the list if abs_path in current: current.remove(abs_path) current.insert(0, abs_path) self.config_parser.set(DEFAULTSECT, RECENT_FILES, (",".join( current[:MAX_NBR_OF_RECENT_FILES_SAVED])).encode(ENCODING)) def get_open_recent_at_startup(self): return self.config_parser.getboolean(DEFAULTSECT, OPEN_RECENT_AT_STARTUP) def set_open_recent_at_startup(self, open): self.config_parser.set(DEFAULTSECT, OPEN_RECENT_AT_STARTUP, str(open)) open_recent_at_startup = property(get_open_recent_at_startup, set_open_recent_at_startup) def get_balloon_on_hover(self): return self.config_parser.getboolean(DEFAULTSECT, BALLOON_ON_HOVER) def set_balloon_on_hover(self, balloon_on_hover): self.config_parser.set(DEFAULTSECT, BALLOON_ON_HOVER, str(balloon_on_hover)) balloon_on_hover = property(get_balloon_on_hover, set_balloon_on_hover) def get_week_start(self): return self.config_parser.get(DEFAULTSECT, WEEK_START) def set_week_start(self, week_start): if not week_start in ["monday", "sunday"]: raise ValueError("Invalid week start.") self.config_parser.set(DEFAULTSECT, WEEK_START, week_start) week_start = property(get_week_start, set_week_start) def get_use_inertial_scrolling(self): return self.config_parser.getboolean(DEFAULTSECT, USE_INERTIAL_SCROLLING) def set_use_inertial_scrolling(self, value): self.config_parser.set(DEFAULTSECT, USE_INERTIAL_SCROLLING, str(value)) use_inertial_scrolling = property(get_use_inertial_scrolling, set_use_inertial_scrolling) def get_shortcut_key(self, cfgid, default): try: return self.config_parser.get(DEFAULTSECT, cfgid) except: self.set_shortcut_key(cfgid, default) return default def set_shortcut_key(self, cfgid, value): self.config_parser.set(DEFAULTSECT, cfgid, value)
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 llvm = True try:
class Config(object): _default_section = 'app' _default_config_file_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'default.ini')) def __init__(self, auto_save=True, path=None): if not path: if 'GRAB_SCREEN_CONFIG_FILE' in os.environ: path = os.environ['GRAB_SCREEN_CONFIG_FILE'] else: path = os.path.join(os.path.expanduser('~'), '.config', 'grab-screen', 'config.ini') self.auto_save = auto_save self.path = path self._parser = None self.load() def __iter__(self): for section in self._parser.sections(): for option in self._parser.options(section): key = '{}_{}'.format(section, option).upper() yield key def __getattribute__(self, key): if key.isupper(): return self.get(key) return object.__getattribute__(self, key) def __setattr__(self, key, value): if key.isupper(): return self.set(key, value) return object.__setattr__(self, key, value) def __delattr__(self, key): if key.isupper(): return self.delete(key) return object.__delattr__(self, key) def get(self, key): """Gets an option.""" section, option = self._split_key(key) if not self._parser.has_option(section, option): return None return self._parser.get(section, option) def set(self, key, value): """Sets an option.""" if value is None: self.delete(key) return section, option = self._split_key(key) self._parser.set(section, option, str(value)) if self.auto_save: self.save() def delete(self, key): """Deletes an option.""" section, option = self._split_key(key) removed = self._parser.remove_option(section, option) if removed and self.auto_save: self.save() def load(self): """Reads settings from the file.""" if not os.path.exists(self.path): self.reset() return self._parser = ConfigParser() self._parser.read(self.path) self._load_logger() def save(self): """Writes settings to the file.""" self._create_config_directory() for section in self._parser.sections(): if not self._parser.options(section): self._parser.remove_section(section) with open(self.path, 'w') as config_file: self._parser.write(config_file) def reset(self): """Restores the default settings.""" self._create_config_directory() copyfile(self._default_config_file_path, self.path) self.load() def _create_config_directory(self): directory = os.path.dirname(self.path) if not os.path.exists(directory): os.makedirs(directory) def _load_logger(self): """ Setup the logger configs. User can set `LOGGER_LEVEL` setting to change the logger level. """ level = self.LOGGER_LEVEL if level: level = level.upper() if level not in LOGGER_LEVELS: logger.warning("Invalid logger level '%s'", level) level = DEFAULT_LEVEL logging.config.dictConfig({ 'version': 1, 'formatters': { 'simple': { 'format': '%(asctime)s [%(levelname)s] %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'simple', }, }, 'loggers': { 'grab_screen': { 'level': level, 'handlers': ['console'], }, } }) def _split_key(self, key): """Gets a section and an option names by the key.""" key = key.lower() try: section, option = key.split('_', 1) except (ValueError, IndexError): section = self._default_section option = key if not self._parser.has_section(section): self._parser.add_section(section) return section, option
parser.add_argument('--sunset', help='Set the sunset time in format hh:mm') args = parser.parse_args() filename = expanduser('~/assistant-helper/smarthome.ini') section = 'light_' + args.sensor config = ConfigParser() config.read(filename) # setter if args.sunrise or args.sunset: if not config.has_section(section): config.add_section(section) config.set(section, 'sunrise', args.sunrise) config.set(section, 'sunset', args.sunset) with open(filename, 'w') as outfile: config.write(outfile) else: sunrise = config.get(section, 'sunrise') sunset = config.get(section, 'sunset') now = datetime.now() m_today = (now - now.replace(hour=0, minute=0, second=0, microsecond=0)).total_seconds() / 60.0 print json.dumps({ "light_needed": m_today < int(sunrise[:-3]) * 60 + int(sunrise[-2:]) or m_today > int(sunset[:-3]) * 3600 + int(sunset[-2:]), "sunrise": sunrise, "sunset": sunset })
class SFLvaultConfig(object): """This object deals with everything configuration. It handles the aliases adding/removal and talks with other systems through Exceptions. It handles the keyring support and passwords management """ def __init__(self, config_file): self.config_file = os.path.expanduser(config_file) self.config_check() self.config_read() def config_check(self): """Checks for ownership and modes for all paths and files, à-la SSH""" fullfile = self.config_file fullpath = os.path.dirname(self.config_file) if not os.path.exists(fullpath): os.makedirs(fullpath, mode=0700) if not os.stat(fullpath)[0] & 0700: ### TODO: RAISE EXCEPTION INSTEAD print "Modes for %s must be 0700 (-rwx------)" % fullpath sys.exit() if not os.path.exists(fullfile): fp = open(fullfile, 'w') fp.write("[SFLvault]\n") fp.close() os.chmod(fullfile, 0600) if not os.stat(fullfile)[0] & 0600: # TODO: raise exception instead. print "Modes for %s must be 0600 (-rw-------)" % fullfile sys.exit() def config_read(self): """Return the ConfigParser object, fully loaded""" self.cfg = ConfigParser() fp = open(self.config_file, 'r') self.cfg.readfp(fp) fp.close() if not self.cfg.has_section('SFLvault'): self.cfg.add_section('SFLvault') if not self.cfg.has_section('Aliases'): self.cfg.add_section('Aliases') if not self.cfg.has_option('SFLvault', 'username'): self.cfg.set('SFLvault', 'username', '') if not self.cfg.has_option('SFLvault', 'url'): self.cfg.set('SFLvault', 'url', '') def config_write(self): """Write the ConfigParser element to disk.""" fp = open(self.config_file, 'w') self.cfg.write(fp) fp.close() # Fake being the actual ConfigParser object def get(self, *args, **kwargs): return self.cfg.get(*args, **kwargs) def set(self, *args, **kwargs): return self.cfg.set(*args, **kwargs) def has_option(self, *args, **kwargs): return self.cfg.has_option(*args, **kwargs) def alias_add(self, alias, ptr): """Add an alias and save config.""" tid = re.match(r'(.)#(\d+)', ptr) if not tid: raise ValueError("VaultID must be in the format: (.)#(\d+)") # Set the alias value self.cfg.set('Aliases', alias, ptr) # Save config. self.config_write() return True def alias_del(self, alias): """Remove an alias from the config. :rtype: True if removed, False otherwise. """ if self.cfg.has_option('Aliases', alias): self.cfg.remove_option('Aliases', alias) self.config_write() return True else: return False def alias_list(self): """Return a list of aliases :rtype: list of (alias, value) pairs. """ return self.cfg.items('Aliases') def alias_get(self, alias): """Return the pointer for a given alias""" if not self.cfg.has_option('Aliases', alias): return None else: return self.cfg.get('Aliases', alias) def _check_keyring(self): try: import keyring except ImportError, e: raise KeyringError("No keyring support, please install python-keyring")
def writeIniFile(self, inputDict, totError): arcpy.AddMessage("\n") arcpy.AddMessage("Creating .ini file") config = ConfigParser() config.add_section('PARAMETERS') for key in inputDict.keys(): config.set('PARAMETERS', key, inputDict[key]) if inputDict['isSearchable'] == 'true': config.add_section('ERROR COUNTS') config.set('ERROR COUNTS', 'General', totError.generalErrorCount) config.set('ERROR COUNTS', 'Geometric', totError.geometricErrorCount) config.set('ERROR COUNTS', 'Address', totError.addressErrorCount) config.set('ERROR COUNTS', 'Tax', totError.taxErrorCount) config.add_section('PERCENT TAXROLL YEAR') config.set( 'PERCENT TAXROLL YEAR', 'Previous', round((float(totError.trYearPast / float( (totError.recordTotalCount - totError.pinSkipCount))) * 100), 2)) config.set( 'PERCENT TAXROLL YEAR', 'Expected', round((float(totError.trYearExpected / float( (totError.recordTotalCount - totError.pinSkipCount))) * 100), 2)) config.set( 'PERCENT TAXROLL YEAR', 'Future', round((float(totError.trYearFuture / float( (totError.recordTotalCount - totError.pinSkipCount))) * 100), 2)) config.set( 'PERCENT TAXROLL YEAR', 'Other', round((float(totError.trYearOther / float( (totError.recordTotalCount - totError.pinSkipCount))) * 100), 2)) config.add_section('MISSING RECORDS') config.set('MISSING RECORDS', 'CONAME', totError.coNameMiss) config.set('MISSING RECORDS', 'PARCELFIPS', totError.fipsMiss) config.set('MISSING RECORDS', 'PARCELSOURCE', totError.srcMiss) config.add_section('COMPARISON COMPLETENESS') for field in totError.comparisonDict.keys(): if field != 'state' or field != 'loaddate': config.set('COMPARISON COMPLETENESS', field, totError.comparisonDict[field]) try: #Write out .ini file with open( inputDict['outINIDir'] + '/' + inputDict['county'] + '_' + inputDict['outName'] + '.ini', 'w') as configFile: config.write(configFile) with open(inputDict['inCert'], 'r') as certFile: for line in certFile: configFile.write(line) arcpy.AddMessage("\n") arcpy.AddMessage("Wrote .ini file to " + inputDict['outINIDir']) arcpy.AddMessage("\n") arcpy.AddMessage("SUBMISSIONS WITHOUT .ini WILL NOT BE ACCEPTED!") arcpy.AddMessage("\n\n") arcpy.AddMessage( "------> .ini FILE CREATION COMPLETE! GREAT WORK!! <------") arcpy.AddMessage("\n\n") except Exception as e: arcpy.AddMessage("!!!!!!!!!!Error writing .ini file!!!!!!!!!!") arcpy.AddMessage(str(e))
response_json['Longitude'] = float(longitude) del (response_json['loc']) del (response_json['postal']) del (response_json['org']) response_json['UnitPreference'] = "METRIC" return response_json response = 0 try: response = urllib2.urlopen(url) response_json = json.loads(response.read()) except Exception as e: print "Error : Error retieving location (Check Connection) , ", e ''' Update the config file once the location is recieved. ''' if response: config = ConfigParser() config.read(config_file) requestinfo = parse_response(response_json) for key in response_json.keys(): config.set('Location', key, response_json[key]) config.set('RequestInfo', 'requestinfo', json.dumps(requestinfo)) with open(config_file, 'w') as f: config.write(f) print "INFO : Location Updated."
class RepositoryZypper(RepositoryBase): """ Implements repo handling for zypper package manager """ def post_init(self, custom_args=None): self.custom_args = custom_args if not custom_args: self.custom_args = [] self.repo_names = [] # zypper support by default point all actions into the root # directory of the image system. This information is passed # as arguments to zypper and adapted if the call runs as # chrooted operation. Therefore the use of the shared location # via RootBind::mount_shared_directory is optional but # recommended to make use of the repo cache manager_base = self.root_dir + self.shared_location self.shared_zypper_dir = { 'pkg-cache-dir': manager_base + '/packages', 'reposd-dir': manager_base + '/zypper/repos', 'solv-cache-dir': manager_base + '/zypper/solv', 'raw-cache-dir': manager_base + '/zypper/raw', 'cache-dir': manager_base + '/zypper' } self.runtime_zypper_config_file = NamedTemporaryFile(dir=self.root_dir) self.runtime_zypp_config_file = NamedTemporaryFile(dir=self.root_dir) self.zypper_args = [ '--non-interactive', '--no-gpg-checks', '--pkg-cache-dir', self.shared_zypper_dir['pkg-cache-dir'], '--reposd-dir', self.shared_zypper_dir['reposd-dir'], '--solv-cache-dir', self.shared_zypper_dir['solv-cache-dir'], '--cache-dir', self.shared_zypper_dir['cache-dir'], '--raw-cache-dir', self.shared_zypper_dir['raw-cache-dir'], '--config', self.runtime_zypper_config_file.name ] + self.custom_args self.command_env = self.__create_zypper_runtime_environment() # config file parameters for zypper tool self.runtime_zypper_config = ConfigParser() self.runtime_zypper_config.add_section('main') # config file parameters for libzypp library self.runtime_zypp_config = ConfigParser() self.runtime_zypp_config.add_section('main') self.runtime_zypp_config.set('main', 'cachedir', self.shared_zypper_dir['cache-dir']) self.runtime_zypp_config.set('main', 'metadatadir', self.shared_zypper_dir['raw-cache-dir']) self.runtime_zypp_config.set('main', 'solvfilesdir', self.shared_zypper_dir['solv-cache-dir']) self.runtime_zypp_config.set('main', 'packagesdir', self.shared_zypper_dir['pkg-cache-dir']) self.__write_runtime_config() def runtime_config(self): return { 'zypper_args': self.zypper_args, 'command_env': self.command_env } def add_repo(self, name, uri, repo_type='rpm-md', prio=None): repo_file = self.shared_zypper_dir['reposd-dir'] + '/' + name + '.repo' self.repo_names.append(name + '.repo') if 'iso-mount' in uri: # iso mount point is a tmpdir, thus different each time we build Path.wipe(repo_file) if not os.path.exists(repo_file): Command.run(['zypper'] + self.zypper_args + [ '--root', self.root_dir, 'addrepo', '-f', '--type', self.__translate_repo_type(repo_type), '--keep-packages', uri, name ], self.command_env) if prio: Command.run(['zypper'] + self.zypper_args + [ '--root', self.root_dir, 'modifyrepo', '-p', format(prio), name ], self.command_env) def delete_repo(self, name): Command.run(['zypper'] + self.zypper_args + ['--root', self.root_dir, 'removerepo', name], self.command_env) def delete_all_repos(self): Path.wipe(self.shared_zypper_dir['reposd-dir']) Path.create(self.shared_zypper_dir['reposd-dir']) def cleanup_unused_repos(self): # zypper creates a system solvable which is unwanted for the # purpose of building images. In addition zypper fails with # an error message 'Failed to cache rpm database' if such a # system solvable exists and a new root system is created solv_dir = self.shared_zypper_dir['solv-cache-dir'] Path.wipe(solv_dir + '/@System') # repository configurations which are not used for this build # must be removed otherwise they are taken into account for # the package installations repos_dir = self.shared_zypper_dir['reposd-dir'] for elements in os.walk(repos_dir): for repo_file in list(elements[2]): if repo_file not in self.repo_names: Path.wipe(repos_dir + '/' + repo_file) break def __create_zypper_runtime_environment(self): for zypper_dir in self.shared_zypper_dir.values(): Path.create(zypper_dir) return dict(os.environ, LANG='C', ZYPP_CONF=self.runtime_zypp_config_file.name) def __write_runtime_config(self): with open(self.runtime_zypper_config_file.name, 'w') as config: self.runtime_zypper_config.write(config) with open(self.runtime_zypp_config_file.name, 'w') as config: self.runtime_zypp_config.write(config) def __translate_repo_type(self, repo_type): """ Translate kiwi supported common repo type names from the schema into the name the zyper package manager understands """ zypper_type_for = { 'rpm-md': 'YUM', 'rpm-dir': 'Plaindir', 'yast2': 'YaST' } try: return zypper_type_for[repo_type] except Exception: raise KiwiRepoTypeUnknown('Unsupported zypper repo type: %s' % repo_type)
'opencv.cv', 'opencv.highgui', ): testimport(x) title('Core selection') report.append('Audio = %s' % SoundLoader._classes) report.append('Camera = %s' % Camera) report.append('Image = %s' % ImageLoader.loaders) report.append('Text = %s' % Label) report.append('Video = %s' % Video) report.append('Window = %s' % MTWindow) title('Configuration') s = StringIO() ConfigParser.write(pymt_config, s) report.extend(s.getvalue().split('\n')) title('Input availability') for x in TouchFactory.list(): report.append(x) title('Log') for x in pymt_logger_history.history: report.append(x.message) title('Environ') for k, v in os.environ.iteritems(): report.append('%s = %s' % (k, v)) title('Options')
def config_load(self): config_file = self.install_dir + '/' + self.game_name + '/config.ini' config_parser = ConfigParser() config_parser.read(config_file) if not config_parser.has_section('Settings'): config_parser.add_section('Settings') if not config_parser.has_option('Settings', 'wine'): self.wine = 'global' config_parser.set('Settings', 'wine', str(self.wine)) else: self.wine = config_parser.get('Settings', 'wine') if not config_parser.has_option('Settings', 'wine_path'): self.wine_path = global_wine_path config_parser.set('Settings', 'wine_path', str(self.wine_path)) else: self.wine_path = config_parser.get('Settings', 'wine_path') if not config_parser.has_option('Settings', 'wine_version'): self.wine_version = global_wine_version config_parser.set('Settings', 'wine_version', str(self.wine_version)) else: self.wine_version = config_parser.get('Settings', 'wine_version') if not config_parser.has_option('Settings', 'monitor'): self.monitor = global_monitor config_parser.set('Settings', 'monitor', str(self.monitor)) else: self.monitor = config_parser.getint('Settings', 'monitor') if not config_parser.has_option('Settings', 'launcher'): self.launcher = True config_parser.set('Settings', 'launcher', str(self.launcher)) else: self.launcher = config_parser.getboolean('Settings', 'launcher') if not config_parser.has_option('Settings', 'show_banner'): self.show_banner = True config_parser.set('Settings', 'show_banner', str(self.show_banner)) else: self.show_banner = config_parser.getboolean('Settings', 'show_banner') if not config_parser.has_option('Settings', 'win_ver'): self.win_ver = 0 config_parser.set('Settings', 'win_ver', str(self.win_ver)) else: self.win_ver = config_parser.getint('Settings', 'win_ver') if not config_parser.has_option('Settings', 'virtual_desktop'): self.virtual_desktop = False config_parser.set('Settings', 'virtual_desktop', str(self.virtual_desktop)) else: self.virtual_desktop = config_parser.getboolean('Settings', 'virtual_desktop') if not config_parser.has_option('Settings', 'virtual_desktop_width'): self.virtual_desktop_width = '' config_parser.set('Settings', 'virtual_desktop_width', str(self.virtual_desktop_width)) else: self.virtual_desktop_width = config_parser.get('Settings', 'virtual_desktop_width') if not config_parser.has_option('Settings', 'virtual_desktop_height'): self.virtual_desktop_height = '' config_parser.set('Settings', 'virtual_desktop_height', str(self.virtual_desktop_height)) else: self.virtual_desktop_height = config_parser.get('Settings', 'virtual_desktop_height') if not config_parser.has_option('Settings', 'mouse_capture'): self.mouse_capture = False config_parser.set('Settings', 'mouse_capture', str(self.mouse_capture)) else: self.mouse_capture = config_parser.getboolean('Settings', 'mouse_capture') if not config_parser.has_option('Settings', 'own_prefix'): self.own_prefix = False config_parser.set('Settings', 'own_prefix', str(self.own_prefix)) else: self.own_prefix = config_parser.getboolean('Settings', 'own_prefix') if not config_parser.has_option('Settings', 'winearch'): self.winearch = 'win32' config_parser.set('Settings', 'winearch', str(self.winearch)) else: self.winearch = config_parser.get('Settings', 'winearch') if not config_parser.has_option('Settings', 'command_before'): self.command_before = '' config_parser.set('Settings', 'command_before', str(self.command_before)) else: self.command_before = config_parser.get('Settings', 'command_before') if not config_parser.has_option('Settings', 'command_after'): self.command_after = '' config_parser.set('Settings', 'command_after', str(self.command_after)) else: self.command_after = config_parser.get('Settings', 'command_after') new_config_file = open(config_file, 'w') config_parser.write(new_config_file) new_config_file.close()
def __init__(self, writeargstofile=False): default_config_file = "config.ini" root_lmfdb_path = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')) if root_lmfdb_path != os.path.abspath(os.getcwd()): default_config_file = os.path.relpath( os.path.join(root_lmfdb_path, default_config_file), os.getcwd()) # 1: parsing command-line arguments parser = argparse.ArgumentParser( description='LMFDB - The L-functions and modular forms database') parser.add_argument('-c', '--config-file', dest="config_file", metavar="FILE", help='configuration file [default: %(default)s]', default=default_config_file) parser.add_argument('-d', '--debug', action="store_true", dest='core_debug', help='enable debug mode') parser.add_argument( '-p', '--port', dest='web_port', metavar='PORT', help= 'the LMFDB server will be running on PORT [default: %(default)d]', type=int, default=37777) parser.add_argument( '-b', '--bind_ip', dest='web_bindip', metavar='HOST', help= 'the LMFDB server will be listening to HOST [default: %(default)s]', default='127.0.0.1') logginggroup = parser.add_argument_group('Logging options:') logginggroup.add_argument( '--logfile', help='logfile for flask [default: %(default)s]', dest='logging_logfile', metavar='FILE', default='flasklog') logginggroup.add_argument('--logfocus', help='name of a logger to focus on', default=argparse.SUPPRESS) # MongoDB options mongodbgroup = parser.add_argument_group('MongoDB options') mongodbgroup.add_argument( '--mongodb-host', dest='mongodb_host', metavar='HOST', help='MongoDB server host [default: %(default)s]', default='m0.lmfdb.xyz') mongodbgroup.add_argument( '--mongodb-port', dest='mongodb_port', metavar='PORT', type=int, help='MongoDB server port [default: %(default)d]', default=27017) mongodbgroup.add_argument( '--dbmon', dest='mongodb_dbmon', metavar='NAME', help= 'monitor MongoDB commands to the specified database (use NAME=* to monitor everything, NAME=~DB to monitor all but DB)', default=argparse.SUPPRESS) # PostgresSQL options postgresqlgroup = parser.add_argument_group('PostgreSQL options') postgresqlgroup.add_argument( '--postgresql-host', dest='postgresql_host', metavar='HOST', help= 'PostgreSQL server host or socket directory [default: %(default)s]', default='devmirror.lmfdb.xyz') postgresqlgroup.add_argument( '--postgresql-port', dest='postgresql_port', metavar='PORT', type=int, help='PostgreSQL server port [default: %(default)d]', default=5432) postgresqlgroup.add_argument( '--postgresql-user', dest='postgresql_user', metavar='USER', help='PostgreSQL username [default: %(default)s]', default="lmfdb") postgresqlgroup.add_argument( '--postgresql-pass', dest='postgresql_password', metavar='PASS', help='PostgreSQL password [default: %(default)s]', default="lmfdb") # undocumented options parser.add_argument('--enable-profiler', dest='profiler', help=argparse.SUPPRESS, action='store_true', default=argparse.SUPPRESS) # undocumented flask options parser.add_argument('--enable-reloader', dest='use_reloader', help=argparse.SUPPRESS, action='store_true', default=argparse.SUPPRESS) parser.add_argument('--disable-reloader', dest='use_reloader', help=argparse.SUPPRESS, action='store_false', default=argparse.SUPPRESS) parser.add_argument('--enable-debugger', dest='use_debugger', help=argparse.SUPPRESS, action='store_true', default=argparse.SUPPRESS) parser.add_argument('--disable-debugger', dest='use_debugger', help=argparse.SUPPRESS, action='store_false', default=argparse.SUPPRESS) if os.path.split( sys.argv[0])[-1] == "start-lmfdb.py" or writeargstofile: args = parser.parse_args() else: # only read config file args = parser.parse_args([]) args_dict = vars(args) default_arguments_dict = vars(parser.parse_args([])) if writeargstofile: default_arguments_dict = dict(args_dict) del default_arguments_dict['config_file'] self.default_args = {} for key, val in default_arguments_dict.iteritems(): sec, opt = key.split('_', 1) if sec not in self.default_args: self.default_args[sec] = {} self.default_args[sec][opt] = str(val) from ConfigParser import ConfigParser # reading the config file, creating it if necessary # 2/1: does config file exist? if not os.path.exists(args.config_file): if not writeargstofile: print( "Config file: %s not found, creating it with the default values" % args.config_file) else: print( "Config file: %s not found, creating it with the passed values" % args.config_file) _cfgp = ConfigParser() # create sections _cfgp.add_section('core') _cfgp.add_section('web') _cfgp.add_section('mongodb') _cfgp.add_section('postgresql') _cfgp.add_section('logging') for sec, options in self.default_args.iteritems(): for opt, val in options.iteritems(): _cfgp.set(sec, opt, str(val)) with open(args.config_file, 'wb') as configfile: _cfgp.write(configfile) # 2/2: reading the config file _cfgp = ConfigParser() _cfgp.read(args.config_file) # 3: override specific settings for key, val in default_arguments_dict.iteritems(): # if a nondefault value was passed through command line arguments set it if args_dict[key] != val: sec, opt = key.split('_') _cfgp.set(sec, opt, str(args_dict[key])) # some generic functions def get(section, key): return _cfgp.get(section, key) def getint(section, key): return _cfgp.getint(section, key) def getboolean(section, key): return _cfgp.getboolean(section, key) def all(sep='_'): ret = {} for s in _cfgp.sections(): for k, v in _cfgp.items(s): ret['%s%s%s' % (s, sep, k)] = v return ret self.flask_options = { "port": getint('web', 'port'), "host": get('web', 'bindip'), "debug": getboolean('core', 'debug') } for opt in ['use_debugger', 'use_reloader', 'profiler']: if opt in args_dict: self.flask_options[opt] = args_dict[opt] self.mongodb_options = { "port": getint("mongodb", "port"), "host": get("mongodb", "host"), "replicaset": None } if "mongodb_dbmon" in args_dict: self.mongodb_options["mongodb_dbmon"] = args_dict["mongodb_dbmon"] self.postgresql_options = { "port": getint("postgresql", "port"), "host": get("postgresql", "host"), "dbname": "lmfdb" } # optional items for elt in ['user', 'password']: if _cfgp.has_option("postgresql", elt): self.postgresql_options[elt] = get("postgresql", elt) self.logging_options = {'logfile': get('logging', 'logfile')} if "logfocus" in args_dict: self.logging_options["logfocus"] = args_dict["logfocus"] if _cfgp.has_option("logging", "editor"): self.logging_options["editor"] = get("logging", "editor")
class MyConfig(MyCommon): #---------------------MyConfig::__init__------------------------------------ def __init__(self, filename=None, section=None, simulation=False, log=None): super(MyConfig, self).__init__() self.log = log self.FileName = filename self.Section = section self.Simulation = simulation self.CriticalLock = threading.Lock( ) # Critical Lock (writing conf file) self.InitComplete = False try: if sys.version_info[0] < 3: self.config = ConfigParser() else: self.config = ConfigParser(interpolation=None) self.config.read(self.FileName) if self.Section == None: SectionList = self.GetSections() if len(SectionList): self.Section = SectionList[0] except Exception as e1: self.LogErrorLine("Error in MyConfig:init: " + str(e1)) return self.InitComplete = True #---------------------MyConfig::HasOption----------------------------------- def HasOption(self, Entry): return self.config.has_option(self.Section, Entry) #---------------------MyConfig::GetList------------------------------------- def GetList(self): try: return self.config.items(self.Section) except Exception as e1: self.LogErrorLine("Error in MyConfig:GetList: " + self.Section + ": " + str(e1)) return None #---------------------MyConfig::GetSections--------------------------------- def GetSections(self): return self.config.sections() #---------------------MyConfig::SetSection---------------------------------- def SetSection(self, section): if self.Simulation: return True if not (isinstance(section, str) or isinstance(section, unicode)) or not len(section): self.LogError("Error in MyConfig:ReadValue: invalid section: " + str(section)) return False self.Section = section return True #---------------------MyConfig::ReadValue----------------------------------- def ReadValue(self, Entry, return_type=str, default=None, section=None, NoLog=False): try: if section != None: self.SetSection(section) if self.config.has_option(self.Section, Entry): if return_type == str: return self.config.get(self.Section, Entry) elif return_type == bool: return self.config.getboolean(self.Section, Entry) elif return_type == float: return self.config.getfloat(self.Section, Entry) elif return_type == int: return self.config.getint(self.Section, Entry) else: self.LogErrorLine( "Warning in MyConfig:ReadValue: invalid type or missing value, using default :" + str(return_type)) return default else: return default except Exception as e1: if not NoLog: self.LogErrorLine("Error in MyConfig:ReadValue: " + self.Section + ": " + Entry + ": " + str(e1)) return default #---------------------MyConfig::WriteSection-------------------------------- # NOTE: This will remove comments from the config file def alt_WriteSection(self, SectionName): if self.Simulation: return True if not self.InitComplete: return False SectionList = self.GetSections() if SectionName in SectionList: self.LogError("Error in WriteSection: Section already exist.") return True try: with self.CriticalLock: # open in unbuffered mode with open(self.FileName, "w") as ConfigFile: if sys.version_info.major < 3: self.config.add_section(SectionName) else: self.config[SectionName] = {} self.config.write(ConfigFile) return True except Exception as e1: self.LogErrorLine("Error in WriteSection: " + str(e1)) return False #---------------------MyConfig::WriteSection-------------------------------- def WriteSection(self, SectionName): if self.Simulation: return True if not self.InitComplete: return False SectionList = self.GetSections() if SectionName in SectionList: self.LogError("Error in WriteSection: Section already exist.") return True try: with self.CriticalLock: # open in unbuffered mode with open(self.FileName, "a") as ConfigFile: ConfigFile.write("[" + SectionName + "]") ConfigFile.flush() ConfigFile.close() # update the read data that is cached self.config.read(self.FileName) return True except Exception as e1: self.LogErrorLine("Error in WriteSection: " + str(e1)) return False #---------------------MyConfig::WriteValue---------------------------------- # NOTE: This will remove comments from the config file def alt_WriteValue(self, Entry, Value, remove=False, section=None): if self.Simulation: return if not self.InitComplete: return False if section != None: self.SetSection(section) try: with self.CriticalLock: if sys.version_info.major < 3: self.config.set(self.Section, Entry, Value) else: section_data = self.config[self.Section] section_data[Entry] = Value #Write changes back to file with open(self.FileName, "w") as ConfigFile: self.config.write(ConfigFile) return True except Exception as e1: self.LogErrorLine("Error in WriteValue: " + str(e1)) return False #---------------------MyConfig::WriteValue---------------------------------- def WriteValue(self, Entry, Value, remove=False, section=None): if self.Simulation: return if not self.InitComplete: return False if section != None: self.SetSection(section) SectionFound = False try: with self.CriticalLock: Found = False ConfigFile = open(self.FileName, 'r') FileString = ConfigFile.read() ConfigFile.close() # open in unbuffered mode ConfigFile = open(self.FileName, 'w') for line in FileString.splitlines(): if not line.isspace(): # blank lines newLine = line.strip() # strip leading spaces if len(newLine): if not newLine[0] == "#": # not a comment if not SectionFound and not self.LineIsSection( newLine): ConfigFile.write(line + "\n") continue if self.LineIsSection( newLine ) and self.Section.lower( ) != self.GetSectionName(newLine).lower(): if SectionFound and not Found and not remove: # we reached the end of the section ConfigFile.write(Entry + " = " + Value + "\n") Found = True SectionFound = False ConfigFile.write(line + "\n") continue if self.LineIsSection( newLine) and self.Section.lower( ) == self.GetSectionName( newLine).lower(): SectionFound = True ConfigFile.write(line + "\n") continue if not SectionFound: ConfigFile.write(line + "\n") continue items = newLine.split( '=') # split items in line by spaces if len(items) >= 2: items[0] = items[0].strip() if items[0] == Entry: if not remove: ConfigFile.write(Entry + " = " + Value + "\n") Found = True continue ConfigFile.write(line + "\n") # if this is a new entry, then write it to the file, unless we are removing it # this check is if there is not section below the one we are working in, # it will be added to the end of the file if not Found and not remove: ConfigFile.write(Entry + " = " + Value + "\n") ConfigFile.flush() ConfigFile.close() # update the read data that is cached self.config.read(self.FileName) return True except Exception as e1: self.LogErrorLine("Error in WriteValue: " + str(e1)) return False #---------------------MyConfig::GetSectionName------------------------------ def GetSectionName(self, Line): if self.Simulation: return "" Line = Line.strip() if Line.startswith("[") and Line.endswith("]") and len(Line) >= 3: Line = Line.replace("[", "") Line = Line.replace("]", "") return Line return "" #---------------------MyConfig::LineIsSection------------------------------- def LineIsSection(self, Line): if self.Simulation: return False Line = Line.strip() if Line.startswith("[") and Line.endswith("]") and len(Line) >= 3: return True return False
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.user_extent is not None \ and self.dock.user_extent_crs is not None: extent = extent_to_array(self.dock.user_extent, self.dock.user_extent_crs) else: extent = viewport_geo_array(self.iface.mapCanvas()) extent_string = ', '.join(('%f' % x) for x in extent) exposure_path = str(self.exposure_layer.publicSource()) hazard_path = str(self.hazard_layer.publicSource()) title = self.keyword_io.read_keywords(self.hazard_layer, 'title') title = safeTr(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 = str( 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) parser.set(title, 'extent_crs', self.dock.user_extent_crs.authid()) if self.aggregation_layer is not None: aggregation_path = str(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 SIDDConfig(object): """ manage SIDD configurations from two sources - default configurations stored in app.cfg in application main directory - user specific configuration stored in my.cfg under user directory """ # default application config file ########################### def __init__(self, config_file): self.config = ConfigParser() self.config_file = config_file self.read_configs() def __del__(self): self.save_configs() # config file operations ########################### def read_configs(self): """ read configuration file in following order 1. default file 2. user file """ #self.config.read(self.DEFAULT_CONFIG_FILE) self.config.read(self.config_file) def save_configs(self): with open(self.config_file, 'w') as config_file: self.config.write(config_file) # config item accesor ########################### def get(self, section, option, default, data_type=types.StringType): """ get configuration value for given section/option set to default if missing type can be used to adjust the type of value read """ return_val = default # retrieve configuration value as an array if data_type == types.ListType: return_val = eval(self.config.get(section, option), {},{}) else: # retrieve configuration as single value if data_type == types.FloatType: get_func = self.config.getfloat elif data_type == types.IntType: get_func = self.config.getint elif data_type == types.BooleanType: get_func = self.config.getboolean else: get_func = self.config.get # retrieve value and cast into appropriate type # return default, if cast fail or config not found try: if self.config.has_option(section, option): return_val = get_func(section, option) except: pass return return_val def set(self, section, option, value): self.config.set(section, option, value)
class mrConfigParser(object): ''' Class to parse config file ''' __config = ConfigParser() __cfgFile = "config.ini" def __init__(self, cfgFile="config.ini"): ''' Constructor @param cfgFile: Filepath of config file ''' self.__config = ConfigParser() # check if file exsists if isfile(cfgFile): self.__config.read(cfgFile) self.__cfgFile = cfgFile def getSections(self): ''' Returns list of section names ''' return self.__config.sections() def getOptions(self, section): ''' Returns list of options in a section ''' if self.__config.has_section(section): return self.__config.options(section) return None def getConfigValue(self, section, option): ''' Returns a config value of a option inside a section ''' if self.__config.has_option(section, option): return self.__config.get(section, option) return None def getConfigValueBool(self, section, option): ''' Returns a boolean config value of a option inside a section ''' if self.__config.has_option(section, option): return self.__config.getboolean(section, option) return None def getConfigValueInt(self, section, option): ''' Returns a integer config value of a option inside a section ''' if self.__config.has_option(section, option): return self.__config.getint(section, option) return None def getConfigValueFloat(self, section, option): ''' Returns a float config value of a option inside a section ''' if self.__config.has_option(section, option): return self.__config.getfloat(section, option) return None def setConfigValue(self, section, option, value): ''' Sets a config Value ''' self.__config.set(section, option, value) def saveConfig(self, cfgFile=None): ''' Saves config to file. @param cfgFile: Filepath of config file. If filepath is None or omitted, config is saved to filepath used at initiation ''' if cfgFile == None: cfgFile = self.__cfgFile fp = open(cfgFile, 'w') self.__config.write(fp) fp.close()
class Config(object): def __init__(self, inifile='data/config.ini'): self.inifile = inifile self.cfg = ConfigParser() with FileLock(self.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': '', 'loginlock': 'off', 'loginfails': 0, 'loginlockexpire': 0, }, 'file': { 'lastdir': '/root', 'lastfile': '', }, } 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): return self.cfg.remove_option(section) def set(self, section, option, value): try: self.cfg.set(section, option, value) except: return False return self.update()
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() storage_dirs = [ ('storage/ceres/dummy.txt', []), ('storage/whisper/dummy.txt',[]), ('storage/lists',[]), ('storage/log/dummy.txt',[]), ('storage/rrd/dummy.txt',[]) ] conf_files = [ ('conf', glob('conf/*.example')) ]
def __init__(self, config="glastopf.cfg", work_dir=os.getcwd()): """ :param work_dir: directory used for data storage and various data files, must be writeable by glastopf. Default: os.getcwd() :param config: path to the glastopf configuration file. Default: glastopf.cfg """ logger.info( 'Initializing Glastopf {0} using "{1}" as work directory.'.format( __version__, work_dir)) self.work_dir = work_dir self.data_dir = os.path.join(self.work_dir, 'data') self.loggers = logging_handler.get_aux_loggers(self.data_dir, self.work_dir) self.config_path = os.path.join(self.work_dir, config) conf_parser = ConfigParser() conf_parser.read(self.config_path) self.options = { "uid": conf_parser.get("webserver", "uid").encode('latin1'), "gid": conf_parser.get("webserver", "gid").encode('latin1'), "proxy_enabled": conf_parser.get("webserver", "proxy_enabled").encode('latin1'), "banner": conf_parser.get("misc", "banner").encode('latin1'), "sensorid": conf_parser.get("sensor", "sensorid").encode('latin1'), } if self.options['sensorid'] == "None": self.options['sensorid'] = str(uuid.uuid4()) conf_parser.set('sensor', 'sensorid', self.options['sensorid']) with open((self.config_path), 'wb') as configfile: conf_parser.write(configfile) (self.maindb, self.dorkdb) = self.setup_main_database(conf_parser) self.dork_generator = self.setup_dork_generator(conf_parser) if len(self.dork_generator.get_current_pages()) == 0: logger.info( "Generating initial dork pages - this can take a while.") self.dork_generator.regular_generate_dork(0) self.profiler_available = False try: self.profiler_available = conf_parser.getboolean( "profiler", "enabled") except (NoSectionError, NoOptionError): pass if self.profiler_available: self.profiler = profiler.Profiler(self.maindb) #self.HTTP_parser = util.HTTPParser() self.MethodHandlers = method_handler.HTTPMethods(self.data_dir) #used for post processing (logging and analysis) of attack events self.post_queue = Queue.Queue() self.workers_enabled = False
def config_load(self): self.start_gn_exists = os.path.exists(self.install_dir + '/' + self.game_name + '/start_gn.sh') self.start_gog_exists = os.path.exists(self.install_dir + '/' + self.game_name + '/start_gog.sh') config_file = self.install_dir + '/' + self.game_name + '/config.ini' config_parser = ConfigParser() config_parser.read(config_file) if not config_parser.has_section('Settings'): config_parser.add_section('Settings') if not config_parser.has_option('Settings', 'launcher_type'): if self.start_gog_exists: self.launcher_type = 'gog' else: self.launcher_type = 'gn' config_parser.set('Settings', 'launcher_type', str(self.launcher_type)) else: self.launcher_type = config_parser.get('Settings', 'launcher_type') if not config_parser.has_option('Settings', 'monitor'): self.monitor = global_monitor config_parser.set('Settings', 'monitor', str(self.monitor)) else: self.monitor = config_parser.getint('Settings', 'monitor') if not config_parser.has_option('Settings', 'launcher'): self.launcher = True config_parser.set('Settings', 'launcher', str(self.launcher)) else: self.launcher = config_parser.getboolean('Settings', 'launcher') if not config_parser.has_option('Settings', 'show_banner'): self.show_banner = True config_parser.set('Settings', 'show_banner', str(self.show_banner)) else: self.show_banner = config_parser.getboolean( 'Settings', 'show_banner') if not config_parser.has_option('Settings', 'command_before'): self.command_before = '' config_parser.set('Settings', 'command_before', str(self.command_before)) else: self.command_before = config_parser.get('Settings', 'command_before') if not config_parser.has_option('Settings', 'command_after'): self.command_after = '' config_parser.set('Settings', 'command_after', str(self.command_after)) else: self.command_after = config_parser.get('Settings', 'command_after') new_config_file = open(config_file, 'w') config_parser.write(new_config_file) new_config_file.close()
# input = csv, output = ConfigParser def csv2config(input, config=None): if not hasattr(input, 'read'): input = csv.StringIO(input) if not config: config = ConfigParser() reader = csv.DictReader(input) for row in reader: section = row[reader.fieldnames[0]] if not config.has_section(section): config.add_section(section) for name, value in row.items(): if value and name != reader.fieldnames[0]: config.set(section, name, value) return config if __name__ == "__main__": # small main program which converts CSV into config.ini format import sys, urllib config = ConfigParser() for input in sys.argv[1:]: csv2config(urllib.urlopen(input), config) config.write(sys.stdout)