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 _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 exportChannel(geo, channel): # Set the template for the file name fileName = '$ENTITY_$CHANNEL_$UDIM' fileExt = '.png' # Check for the project info file cp = ConfigParser() projPath = mari.current.project().info().projectPath()[:-11] cp.read(os.path.join(projPath, ".projectInfo")) exportPath = "" try: # Try and pull the last export path exportPath = cp.get("FilePaths", "Export") except: # If there was none, Prompt user for destination directory exportPath = mari.utils.getExistingDirectory(None, 'Select Map Export Path for \"' + channel.name() + '\"') if(len(exportPath) == 0): return else: # Save it to a project info file projInfo = ConfigParser() projInfo.add_section("FilePaths") projInfo.set("FilePaths", "Export", exportPath) projInfoFile = open(os.path.join(projPath, ".projectInfo"), "wb") projInfo.write(projInfoFile) # Save all images as PNG fullFilePath = exportPath + '/' + fileName + fileExt print fullFilePath channel.exportImagesFlattened(fullFilePath, mari.Image.DISABLE_SMALL_UNIFORMS) # Convert to RAT convertToRat(geo, exportPath + '/' + geo.name() + '_' + channel.name())
def addRegra(self, ipORrede, nome, banda_liberada, banda_down, prio, delimitado, isolado): #system("tc qdisc del dev %s root"%self.device) arquivo = ConfigParser() arquivo.read( '/var/lib/netcontrol/plugins/limite_banda/etc/config_server' ) if not arquivo.has_section("contador_regras"): arquivo.add_section("contador_regras") arquivo.set("contador_regras","contador",1) arquivo.write( open('/var/lib/netcontrol/plugins/limite_banda/etc/config_server','w') ) cont = "1" else: cont = int(arquivo.get("contador_regras", "contador")) + 1 arquivo.set("contador_regras","contador", cont) arquivo.write( open('/var/lib/netcontrol/plugins/limite_banda/etc/config_server','w') ) cont = str(cont) cont = "000%s"%(cont) ip = ipORrede.replace('.','_').replace('/','_') user = nome.replace(' ','_') nome = "cbq-%s.%s%s-in"%(cont[-4:],ip,user) regra = "DEVICE=%s,%s,%s\n" \ "RATE=%sKbit\n" \ "WEIGHT=%sKbit\n" \ "PRIO=%s\n" \ "RULE=%s\n" \ "BOUNDED=%s\n" \ "ISOLATED=%s"%(self.device, self.banda_total, self.banda_total_down, banda_liberada, banda_down, prio, ipORrede, delimitado, isolado) open('%s%s'%(self.etc,nome),'w').write(regra)
def 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()
def test_typical(self): """ Test a non-broken, typical setup """ from ConfigParser import ConfigParser from velouria.config import VelouriaConfigKeyboard from gi.repository import Gdk config = ConfigParser() config.add_section("keyboard") config.set("keyboard", "quit", "META_MASK+KEY_q\nKEY_x") config.set("keyboard", "fullscreen", "CONTROL_MASK+KEY_r") config.set("keyboard", "pause", "") keyconfig = VelouriaConfigKeyboard(config) expected = self._defaults() # override quit and fullscreen actions expected['pause'] = None expected['quit'] = [ {'key': Gdk.KEY_x, 'modifiers': 0}, {'key': Gdk.KEY_q, 'modifiers': Gdk.ModifierType.META_MASK}, ] expected['fullscreen'] = [ {'key': Gdk.KEY_r, 'modifiers': Gdk.ModifierType.CONTROL_MASK}, ] self.assertItemsEqual(expected['quit'], keyconfig.quit) self.assertItemsEqual(expected['fullscreen'], keyconfig.fullscreen) self.assertIsNone(keyconfig.pause)
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'))
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 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 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)
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)
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)
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 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 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 set_auto_rsvp_groups(): '''Generates a group config file from user input. The config file is saved to CONFIG_FILENAME specified above. All groups of the current member are printed to the config file. However, any groups the user doesn't want to auto RSVP will be commented out with a '#'. ''' groups = get_groups() config_groups = [] for group in groups: ans = raw_input( 'Automatically RSVP yes for %s? [y/n]: ' % group['name'] ).lower() while ans not in ['y', 'n']: print 'Please enter a \'y\' or \'n\'.' ans = raw_input( 'Automatically RSVP yes for %s? [y/n]: ' % group['name'] ).lower() if ans == 'y': # We want to auto-rsvp for this group config_groups.append((str(group['id']), group['name'])) else: # Don't auto RSVP. We'll write add this group with a comment # preceding the line. config_groups.append(('#%s' % str(group['id']), group['name'])) config = ConfigParser() config.add_section('rsvp_groups') [config.set('rsvp_groups', group_id, group_name) for group_id, group_name in config_groups] write_config(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 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 config_parser(role='agent'): config_parser = ConfigParser() config_parser.add_section(role) config_parser.set(role, 'APP_ID', '1') config_parser.set(role, 'IPOP_BASE_NAMESPACE', 'http://example.org:443') config_parser.set(role, 'CONPAAS_HOME', IPOP_CONF_DIR) return config_parser
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)
class Playlist(object): def __init__(self, location): dir = os.path.expanduser(os.path.dirname(location)) if not os.path.exists(dir): os.makedirs(dir) self._config = ConfigParser() self._config.optionxform = str self._file = os.path.expanduser(location) if os.path.exists(self._file): self._config.read(self._file) else: self._config.add_section('Playlist') self.save() def save(self): self._config.write(open(self._file, 'wb')) def append(self, item): self._config.set('Playlist', *item) self.save() def remove(self, option): self._config.remove_option('Playlist', option) self.save() def __getitem__(self, item): return self._config.items('Playlist')[item] def __iter__(self): return iter(self._config.items('Playlist'))
def write_last_synced(self, _value, _job, _new, _smb_connection=None): """ Write _value to the last_synced property of the destination status file :param _value: The value to write :param _job: A SyncJob instance :param _new: If there isn't already a history-section :param _smb_connection: An SMB connection. :return: """ if _new is None: if _smb_connection is not None: _file_obj = read_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt')) else: try: _file_obj = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r") except IOError: pass else: _file_obj = StringIO.StringIO() _cfg = ConfigParser() _cfg.readfp(_file_obj) if _new is not None: _cfg.add_section("history") _cfg.set("history", "last_synced", _value) _cfg.write(_file_obj) if _smb_connection is not None: write_string_file_smb(_smb_connection, os.path.join(_job.destination_folder, 'ofs_status.txt'), _file_obj) else: try: _file = open(os.path.join(_job.destination_folder, 'ofs_status.txt'), "r") except IOError: pass
def createNodeInfoFile(dirPath, toKeep): """ Creates the .nodeInfo file in the directory specified by dirPath. The Node:Type must be set by concrete nodes @precondition: dirPath is a valid directory @postcondition: All sections/tags are created and set except "Type". "Type" must be set by concrete nodes. """ username = getUsername() timestamp = time.strftime("%a, %d %b %Y %I:%M:%S %p", time.localtime()) nodeInfo = ConfigParser() nodeInfo.add_section('Node') nodeInfo.set('Node', 'Type', '') nodeInfo.add_section('Versioning') nodeInfo.set('Versioning', 'LatestVersion', '0') nodeInfo.set('Versioning', 'VersionsToKeep', str(toKeep)) nodeInfo.set('Versioning', 'Locked', 'False') nodeInfo.set('Versioning', 'LastCheckoutTime', timestamp) nodeInfo.set('Versioning', 'LastCheckoutUser', username) nodeInfo.set('Versioning', 'LastCheckinTime', timestamp) nodeInfo.set('Versioning', 'LastCheckinUser', username) _writeConfigFile(os.path.join(dirPath, ".nodeInfo"), nodeInfo)
def start_config(config_file_name): config = ConfigParser() config.add_section("global") value = raw_input("Enter the JSON root folder to write the json files too : ") if len(value) == 0: value = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + '/www/JSON' elif value[-1] != "/": value += "/" config.set("global", "json_root", value) modules_config = [] module_list = os.listdir(os.path.dirname(os.path.abspath(__file__))) for module in module_list: if module == "__init__.py" or module[-3:] != ".py" or module[:4] == 'main': continue loaded_module = __import__("pygamescanner." + module[:-3], fromlist=["*"]) module_config = loaded_module.start_config(config) modules_config.append(module_config) modules_config_dict = dict() modules_config_dict["module_list"] = modules_config config_string = json.dumps(modules_config_dict) modules_file = open(config.get("global", "json_root") + "modules.json", "w") modules_file.write(config_string) modules_file.close() config_file = open(config_file_name, "w") config.write(config_file) config_file.close()
def set_config(self, config): cp = ConfigParser() cp.add_section(self.DEFAULT_INI_SECTION) for k, v in config.items(): cp.set(self.DEFAULT_INI_SECTION, k, v) with open(self.ini_file_name, "w") as f: cp.write(f)
def set_config_to_path(configPath, section, option, value): read = False #check if config file exists if ( os.path.isfile(configPath)): configPath = os.path.realpath(configPath); config = ConfigParser(); #try to read the value from ini file try: config.read(configPath) if config.has_section(section) : #Update the new values config.set(section, option, value) read = True except: #read failed due currupted ini file that can happen due to suddent power of during update print "except" if( read == False): #file not exist and needs to be creatred config = ConfigParser(); config.add_section(section) config.set(section, option, value) read = True fo=open(configPath, "w+") config.write(fo) # Write update config return read
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 CreateConfig(self, ): config=ConfigParser() config.add_section('SMTP') config.add_section('SEND') config.add_section('MAIL') config.set('SMTP','Server','smtp.163.com') config.set('SMTP','Port','25') config.set('SMTP','SSL','0') config.set('SEND','Thread','1') config.set('SEND','Per_Sender','4') config.set('SEND','per_email_sleep','10') config.set('SEND','fail_times','4') config.set('SEND','Sender','Sender.txt') config.set('SEND','Receiver','Receiver.txt') config.set('MAIL','PlainOrHtml','html') config.set('MAIL','Subject','Join My Network On Linkedin') config.set('MAIL','DisplayName','Rich Park{%MAILFROM%}') config.set('MAIL','ForgeSource','false') config.set('MAIL','Content','mail.html') config.set('MAIL','Attachment','None') config.write(open(gConfigFileStr,'w')) #config.write(codecs.open(gConfigFileStr,'w')) if not exists('Sender.txt'):open('Sender.txt','a') if not exists('Receiver.txt'):open('Receiver.txt','a') self.__init__()
def build_config(): config = ConfigParser() config.add_section('Modbus Tcp') config.add_section('Modbus Protocol') config.add_section('Modbus Serial') config.set('Modbus Tcp', "ip", '127.0.0.1') config.set('Modbus Protocol', "block start", "0") config.set('Modbus Protocol', "block size", "100") config.set('Modbus Protocol', "bin min", "0") config.set('Modbus Protocol', "bin max", "1") config.set('Modbus Protocol', "reg min", "0") config.set('Modbus Protocol', "reg max", "65535") config.set('Modbus Serial', "baudrate", "9600") config.set('Modbus Serial', "bytesize", "8") config.set('Modbus Serial', "parity", 'N') config.set('Modbus Serial', "stopbits", "1") config.set('Modbus Serial', "xonxoff", "0") config.set('Modbus Serial', "rtscts", "0") config.set('Modbus Serial', "dsrdtr", "0") config.set('Modbus Serial', "writetimeout", "2") config.set('Modbus Serial', "timeout", "2") config.add_section('Logging') # config.set('Logging', "log file", os.path.join(self.user_data_dir, # 'modbus.log')) config.set('Logging', "logging", "1") config.set('Logging', "console logging", "1") config.set('Logging', "console log level", "DEBUG") config.set('Logging', "file log level", "DEBUG") config.set('Logging', "file logging", "1") config.add_section('Simulation') config.set('Simulation', 'time interval', "1") return config
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 _install_desktop_file(self, prefix, activity_path): cp = ConfigParser() section = 'Desktop Entry' cp.add_section(section) cp.optionxform = str # Allow CamelCase entries # Get it from the activity.info for the non-translated version info = ConfigParser() info.read(os.path.join(activity_path, 'activity', 'activity.info')) cp.set(section, 'Name', info.get('Activity', 'name')) if info.has_option('Activity', 'summary'): cp.set(section, 'Comment', info.get('Activity', 'summary')) for path in sorted(glob(os.path.join(activity_path, 'locale', '*', 'activity.linfo'))): locale = path.split(os.path.sep)[-2] info = ConfigParser() info.read(path) if info.has_option('Activity', 'name'): cp.set(section, 'Name[{}]'.format(locale), info.get('Activity', 'name')) if info.has_option('Activity', 'summary'): cp.set(section, 'Comment[{}]'.format(locale), info.get('Activity', 'summary')) cp.set(section, 'Terminal', 'false') cp.set(section, 'Type', 'Application') cp.set(section, 'Categories', 'Education;') cp.set(section, 'Icon', os.path.join( activity_path, 'activity', self.config.bundle.get_icon_filename())) cp.set(section, 'Exec', self.config.bundle.get_command()) cp.set(section, 'Path', activity_path) # Path == CWD for running name = '{}.activity.desktop'.format(self.config.bundle_id) path = os.path.join(prefix, 'share', 'applications', name) if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) with open(path, 'w') as f: cp.write(f)
def residuals(params, data): dummy_band = 'x' config = ConfigParser() sect = "Observatory Position" config.add_section(sect) config.set(sect, 'longitude', str(longitude)) config.set(sect, 'latitude', str(latitude)) sect = "sky" config.add_section(sect) config.set(sect, 'filters', str(dummy_band)) config.set(sect, 'k', str(float(params['k']))) config.set(sect, 'm_inf', str(float(params['m_inf']))) config.set(sect, 'm_zen', str(float(params['m_zen']))) config.set(sect, 'h', str(float(params['h']))) config.set(sect, 'rayl_m', str(float(params['rayl_m']))) config.set(sect, 'g', str(float(params['g']))) config.set(sect, 'mie_m', str(float(params['mie_m']))) config.set(sect, 'sun_dm', str(float(params['sun_dm']))) config.set(sect, 'twi1', str(float(params['twi1']))) config.set(sect, 'twi2', str(float(params['twi2']))) calc_sky = MoonSkyModel(config) calc_sky.twilight_nan = False calc_sky.k[dummy_band] = data.k.values modmag = calc_sky(data.mjd.values, data.telra.values, data.teldec.values, dummy_band) datamag = data.skymag.values resid = modmag - datamag mad = np.median(abs(resid)) stdev = 1.4826 * mad clip_lim = 3 * stdev resid[resid > clip_lim] = clip_lim resid[resid < (-1 * clip_lim)] = -1 * clip_lim return (modmag - datamag)
def setCalibration(self): dialog = CalibrationDialog(self) dialog.setSpinGroupValue(self.calibration) dialog.setSpinGroupValue(self.calibration) dialog.show() dialog.exec_() if not dialog.correct_flag: return self.calibration = dialog.getSpinGroupValue() #print self.calibration config = ConfigParser() try: file = open("./conf/temp.ini", 'a+') config.read(file.name) section = "CALIBRATION" if not config.has_section(section): config.add_section(section) for i, j in enumerate(['pc1', 'pc2', 'pc3', 'pc4', 'pc5', 'pc6']): config.set(section, j, self.calibration[i]) config.write(file) except Exception, e: QMessageBox.information(self, u'读取失败', u'配置文档有误,请重新配置' + str(e))
def gen_build_version(): builddate = time.asctime() cmd = subprocess.Popen(["/usr/bin/git", "log", "--format=%h%n%ad", "-1"], stdout=subprocess.PIPE) data = cmd.communicate()[0].strip() if cmd.returncode == 0: gitstamp, gitdate = data.split("\n") else: gitdate = "?" gitstamp = "?" fd = open(os.path.join(OUTPUT_DIR, "version"), "w+") config = ConfigParser() config.add_section("cobbler") config.set("cobbler", "gitdate", gitdate) config.set("cobbler", "gitstamp", gitstamp) config.set("cobbler", "builddate", builddate) config.set("cobbler", "version", VERSION) config.set("cobbler", "version_tuple", [int(x) for x in VERSION.split(".")]) config.write(fd) fd.close()
def _write_cfg(self, url, configDict): hostname = urlparse(url).hostname weevname = os.path.splitext(os.path.basename(urlsplit(url).path))[0] sessionfile = os.path.join(cfgfilepath, hostname, weevname + cfgext) parser = ConfigParser() try: if not os.path.exists(os.path.join(cfgfilepath, hostname)): os.makedirs(os.path.join(cfgfilepath, hostname)) writer = open(sessionfile, 'w') parser.add_section('global') parser.set('global', 'url', url) for k, v in configDict.iteritems(): parser.set('global', k, v) parser.write(writer) print("[+] Writing session file '%s'\n" % sessionfile) except (IOError, Exception) as e: #print( "[!] Error: %s" % e) print("[!] Error writing '%s' file: \n" % sessionfile)
def loadConfig(self): confpath = os.path.expanduser('~/.gsend/gsend.conf') conf = ConfigParser() if not os.path.exists(confpath): os.makedirs(os.path.expanduser('~/.gsend')) if not os.path.exists(confpath): print >> sys.stderr, "Before using this program, you have to complete the config file." print >> sys.stderr, "The the path of the config file is '~/.gsend/gsend.conf'" conf.add_section("SERVER") conf.add_section("ACCOUNT") conf.add_section("OPTIONS") conf.set('SERVER', 'host', 'smtp.gmail.com') conf.set('SERVER', 'port', 587) conf.set('SERVER', 'tls', True) conf.set('ACCOUNT', 'login', '*****@*****.**') conf.set('ACCOUNT', 'paswd', '') conf.set('OPTIONS', 'email_encoding', 'utf-8') conf.set('OPTIONS', 'file_system_encoding', sys.getfilesystemencoding()) conf.set('OPTIONS', 'attachment_size', 5) conffile = open(confpath, 'w') conf.write(conffile) conffile.close() sys.exit(2) else: conf.read(confpath) self.host = conf.get('SERVER', 'host') self.port = conf.getint('SERVER', 'port') self.tls = conf.getboolean('SERVER', 'tls') self.login = conf.get('ACCOUNT', 'login') self.paswd = conf.get('ACCOUNT', 'paswd') # password is not provided in the conf file, # ask the user to input self.attachment_size = conf.getint('OPTIONS', 'attachment_size') self.encoding = conf.get('OPTIONS', 'email_encoding') self.fsencoding = conf.get('OPTIONS', 'file_system_encoding')
class ConfReader: def __init__(self, config_file): #def __init__(self): #PWD environment var is used in linux/unix OS. #conf_filename = os.path.join(os.environ['PWD'], 'sockets_API.conf') conf_filename = os.path.join(os.environ['PWD'], config_file) #conf_filename = os.path.join(os.environ['HOME'], config_file) self.config = ConfigParser() self.config.add_section("constants") self.config.add_section("functions") self.config.add_section("structures") self.config.add_section("applications") #fname = open(conf_filename,"r") self.config.read([conf_filename]) #Container for keeping all configuration file data. Initial value is empty self.dicContainer = {} #self.config.readfp(fname) def print_test(self): #conf_filename = os.path.join(os.environ['HOME'], 'sockets_API.conf') #config = ConfigParser() #config.add_section("functions") print self.config.get("functions", "socket") def print_test2(self): print self.config.get("functions", "socket") #get key value under the section def getValue(self, section, key): value = self.config.get(section, key) return value #get all items based on section def getItems(self, section): items = self.config.items(section) return items #parse config file based on the section, save the items into dictionary def saveItemsDic(self, section): items = self.getItems(section) try: for item in items: #item[0] is key, item[1] is value self.dicContainer[item[0]] = item[1] """ print item[0] print item[1] """ except: print "Could get items based on section" #return self.dicContainer # get the container which keeps all configuration file data. def getDicContainer(self): return self.dicContainer
def __call__(self, inputs): from ConfigParser import ConfigParser config = ConfigParser() sections = self.get_input('sections') options = self.get_input('options') if type(sections) != list: sections = [sections] if type(options) != list: options = [options] print sections print options assert len(sections) == len(options) for section, option in zip(sections, options): config.add_section(section) for key, value in option.iteritems(): config.set(section, key, str(value)) return config
def write_config(self): """ Overwrite the existing node.cfg with changed values """ source_configuration_file_path = os.path.join(self.install_directory, 'etc', 'node.cfg') if self.backup_configuration_directory: destination_configuration_path = os.path.join( self.backup_configuration_directory, 'node.cfg.d') try: utilities.backup_configuration_file( source_configuration_file_path, destination_configuration_path, destination_file_prefix='node.cfg.backup') except general_exceptions.WriteConfigError: raise zeek_exceptions.WriteZeekConfigError( 'Zeek configuration failed to write [node.cfg].') except general_exceptions.ReadConfigError: raise zeek_exceptions.ReadsZeekConfigError( 'Zeek configuration failed to read [node.cfg].') config = ConfigParser() for section in self.node_config.keys(): for k, v in self.node_config[section].items(): try: config.add_section(section) except Exception: # Duplicate section pass config.set(section, k, str(v)) try: with open(source_configuration_file_path, 'w') as configfile: config.write(configfile) except IOError: raise zeek_exceptions.WriteZeekConfigError( "Could not locate {}".format(self.install_directory)) except Exception as e: raise zeek_exceptions.WriteZeekConfigError( "General error while attempting to write new node.cfg file to {}; {}" .format(self.install_directory, e))
class ConfigExample(object): """Create a simple example of ConfigParser instance to play with :: >>> from easydev.pipeline.config import ConfigExample >>> c = ConfigExample().config # The ConfigParser instance >>> assert 'General' in c.sections() >>> assert 'GA' in c.sections() This example builds up a ConfigParser instance from scratch. This is equivalent to having the following input file:: [General] verbose = True tag = test [GA] popsize = 1 which can be read with ConfigParser as follows: .. doctest:: >>> # Python 3 code >>> from configparser import ConfigParser >>> config = ConfigParser() >>> config.read("file.ini") [] """ def __init__(self): self.config = ConfigParser() self.config.add_section('General') self.config.set('General', 'verbose', 'true') self.config.add_section('GA') self.config.set('GA', 'popsize', '50')
def _update_sample_config(self): from ConfigParser import ConfigParser config = ConfigParser() for section, options in self.config.defaults().items(): config.add_section(section) for name, value in options.items(): config.set(section, name, value) filename = os.path.join(self.env.path, 'conf', 'trac.ini.sample') try: fileobj = file(filename, 'w') try: config.write(fileobj) fileobj.close() finally: fileobj.close() self.log.info( 'Wrote sample configuration file with the new ' 'settings and their default values: %s', filename) except IOError, e: self.log.warn('Couldn\'t write sample configuration file (%s)', e, exc_info=True)
def update_hgrc_paths(self): """Update hgrc paths section if needed. Old paths are kept in renamed form: buildout_save_%d.""" parser = ConfigParser() hgrc_path = os.path.join(self.target_dir, '.hg', 'hgrc') parser.read(hgrc_path) # does not fail if file does not exist previous = None try: previous = parser.get('paths', 'default') except NoOptionError: logger.info("No 'default' value for [paths] in %s, will set one", hgrc_path) except NoSectionError: logger.info("Creating [paths] section in %s", hgrc_path) parser.add_section('paths') if previous == self.url: return if previous is not None: count = 1 while True: save = 'buildout_save_%d' % count try: parser.get('paths', save) except NoOptionError: break count += 1 parser.set('paths', save, previous) logger.info( "Change of origin URL, saving previous value as %r in " "[paths] section of %s", save, hgrc_path) parser.set('paths', 'default', self.url) f = open(hgrc_path, 'w') parser.write(f) f.close()
class ConfigObj(object): """ Implements a dictionary object of (section, item) with the config.ini file """ def __init__(self): self._config_parser = ConfigParser() self.config = {} def _update_dictionary(self): for sect in self._config_parser.sections(): for item_name, value in self._config_parser.items(sect): self.config[(sect, item_name)] = value def __getitem__(self, key): return self.config.get(key, None) def __setitem__(self, key, value): if value is None: value = '' self.config[key] = value (section, item) = key if not self._config_parser.has_section(section): self._config_parser.add_section(section) self._config_parser.set(section, item, value) def __str__(self): return str(self.config) def save(self, filename): self._config_parser.write(open(filename,'wb'))
def query(): vehicle_info = VehicleInfo() try: proto_utils.get_pb_from_text_file("vehicle_info.pb.txt", vehicle_info) except IOError: print "vehicle_info.pb.txt cannot be open file." exit() # setup server url config = ConfigParser() config.read("config.ini") ip = config.get('Host', 'ip') port = config.get('Host', 'port') url = 'http://' + ip + ':' + port + '/query' # setup car info brand = VehicleInfo.Brand.Name(vehicle_info.brand) model = VehicleInfo.Model.Name(vehicle_info.model) vin = vehicle_info.license.vin car_info = { "car_type": brand + "." + model, "tag": os.environ['DOCKER_IMG'], "vin": vin, } r = requests.post(url, data=car_info) if r.status_code == 200: tag = r.json().get("tag") config.add_section('Update') config.set('Update', 'tag', tag) with open('update.ini', 'wb') as update_file: config.write(update_file) elif r.status_code == 204: print "Release is up to date." elif r.status_code == 400: print "Invalid car type." else: print "Cannot connect to server."
def reset(self, name): # If custom conf file is not set then it is only read only configs if self.custom_conf_file is None: raise GconfNotConfigurable() # If a config can not be modified if name != "all" and not self._is_configurable(name): raise GconfNotConfigurable() cnf = ConfigParser() with open(self.custom_conf_file) as f: cnf.readfp(f) # Nothing to Reset, Not configured if name != "all": if not cnf.has_option("vars", name): return True # Remove option from custom conf file cnf.remove_option("vars", name) else: # Remove and add empty section, do not disturb if config file # already has any other section try: cnf.remove_section("vars") except NoSectionError: pass cnf.add_section("vars") with open(self.tmp_conf_file, "w") as fw: cnf.write(fw) os.rename(self.tmp_conf_file, self.custom_conf_file) self.reload() return True
def register_config(): #cfgfile = open(CONFIG_FILE_LOC,'rw') #pdb.set_trace() Config = ConfigParser() Config.read(CONFIG_FILE_LOC) op = op1 = None if not Config.has_section('160by2'): op = raw_input(">>> Do you have 160by2 Account ?(y/n):") if op and op[0] == 'y': username = raw_input(">>> Enter UserName:"******">>> Enter Password:"******">>> Do you have way2sms Account ?(y/n):") if op1 and op1[0] == 'y': username = raw_input(">>> Enter UserName:"******">>> Enter Password:") conn = getSmsHandaler(username, password, provider='way2sms') if conn and conn.is_auth: Config.add_section('way2sms') Config.set('way2sms', 'uname', username) Config.set('way2sms', 'password', password) print '>>> Congrts! You have successfully setup the configuration.\n\n' else: print '>>> Oops, You are not able to Autheticate.' if not op and not op1: print '>>> You Should have either 160by2 or way2sms account to use this apps.' #with open(CONFIG_FILE_LOC, 'wb') as configfile: with os.fdopen(os.open(CONFIG_FILE_LOC, os.O_WRONLY | os.O_CREAT, 0777), 'wb') as configfile: Config.write(configfile)
def __enter__(self): assert self.filename is None cp = ConfigParser() cp.add_section(self.section) cp.set(self.section, 'address', self.address) cp.set(self.section, 'port', self.port) cp.set(self.section, 'log_level', logging.getLevelName(self.logging_level)) cp.set(self.section, 'max_concurrent_executing_http_requests', self.max_concurrent_executing_http_requests) cp.set(self.section, 'docker_remote_api', self.docker_remote_api) cp.set(self.section, 'docker_remote_api_connect_timeout', self.docker_remote_api_connect_timeout) cp.set(self.section, 'docker_remote_api_request_timeout', self.docker_remote_api_request_timeout) self.filename = tempfile.mktemp() with open(self.filename, 'w+') as fp: cp.write(fp) return self
def write_subsystem_config(managers, path, append=True): cfgp = ConfigParser() if append: with open(path, "r") as cfgf: cfgp.read(cfgf) for mngr in managers: sec = mngr.full_name() cfgp.add_section(sec) #for a in ["instrument", "sample_rate", "configuration_file", "dq_channel", "on_bits", "off_bits", "priority"]: for a in [ "instrument", "sample_rate", "downsample_rate", "configuration_file", "dq_channel", "on_bits", "off_bits", "shm_part_name" ]: #, "priority"]: val = getattr(mngr, a) cfgp.set(sec, a, "" if val is None else val) if hasattr(path, "write"): cfgp.write(path) return with open(path, "w") as fout: cfgp.write(fout)
def create_boto_config(path, aws_access_key_id, aws_secret_access_key, region): config = ConfigParser() config.add_section('Credentials') config.set('Credentials', 'aws_access_key_id', aws_access_key_id) config.set('Credentials', 'aws_secret_access_key', aws_secret_access_key) config.add_section('Boto') config.set('Boto', 'ec2_region_name', region) directory = os.path.dirname(path) if not os.path.exists(directory): os.makedirs(directory) with open(path, 'w+') as fh: config.write(fh) os.chown(path, UID, GID) print "Created boto configuration at {}".format(path)
def loadConfig(): ## Construct filename for user config file filename = os.path.join(os.environ['HOME'], '.libwfutrc') config = ConfigParser() ## TODO: Move into a setDefaults() method? ## Set some default values config.add_section("general") config.set("general", "server_root", "http://white.worldforgedev.org/WFUT/") ## Read user config file. config.read([filename]) ## TODO: We do not need to do this all the time... ## Save config file fp = open(filename, "w") config.write(fp) fp.close() return config
def savecfg(self): cfg = ConfigParser() cfg.add_section('userconfig') cfg.set('userconfig', 'loadlasttime', str(self.loadlasttime)) cfg.set('userconfig', 'openremote', str(self.openremote)) if self.fontfamily: cfg.set('userconfig', 'fontfamily', self.fontfamily.encode('utf-8')) if self.fontsize: cfg.set('userconfig', 'fontsize', str(self.fontsize)) cfg.set('userconfig', 'lastdir', self.__lastdir) cfg.set('userconfig', 'default_search_engine', self.sengine_own) cfg.add_section('searchext') for a, b in self.searchext.iteritems(): cfg.set('searchext', a, str(b)) try: os.mkdir(cfghome, 0700) except exceptions.OSError: pass f = open(globalcfgfile, 'wb') cfg.write(f) f.flush() f.close()
def SetConfigs( configs): """ Method used to set configuration directives in INI file kb_config Takes as a parameter a dictionary of config directives within the authentication section that need to be set/unset. If there is a dictionary entry where the value is None then the config setting will be deleted """ global kb_config,authdata,tokenenv,AuthSvcHost,RolesSvcHost global RoleSvcURL,nexusconfig,conf conf = ConfigParser() if os.path.exists( kb_config): conf.read(kb_config) if not conf.has_section('authentication'): conf.add_section('authentication') for key in configs.keys(): if configs[key] is not None: conf.set('authentication',key, configs[key]) else: conf.remove_option('authentication',key) with open(kb_config, 'wb') as configfile: conf.write(configfile) LoadConfig()
def pytest_funcarg__config(request): "Prepare a configuration parser object." cfg = ConfigParser() cfg.add_section(C.DATASTORE) cfg.set(C.DATASTORE, C.SCALE_FACTOR, '10000000') cfg.set(C.DATASTORE, C.CHANGESETS_INLINE_SIZE, '1024') cfg.set(C.DATASTORE, C.CHANGESETS_PER_SLAB, '8') cfg.set(C.DATASTORE, C.NODES_INLINE_SIZE, '1024') cfg.set(C.DATASTORE, C.NODES_PER_SLAB, '8') cfg.set(C.DATASTORE, C.RELATIONS_INLINE_SIZE, '1024') cfg.set(C.DATASTORE, C.RELATIONS_PER_SLAB, '8') cfg.set(C.DATASTORE, C.WAYS_INLINE_SIZE, '1024') cfg.set(C.DATASTORE, C.WAYS_PER_SLAB, '8') cfg.add_section(C.FRONT_END) cfg.set(C.FRONT_END, C.SERVER_VERSION, '0.6') cfg.set(C.FRONT_END, C.SERVER_NAME, 'Test') slabutil_init(cfg) return cfg
def write_config(self): """ Overwrite the existing node.cfg with changed values """ config = ConfigParser() for section in self.node_config.keys(): for k, v in self.node_config[section].items(): try: config.add_section(section) except Exception: # Duplicate section pass config.set(section, k, str(v)) try: with open(os.path.join(self.install_directory, 'etc', 'node.cfg'), 'w') as configfile: config.write(configfile) except IOError: raise zeek_exceptions.WriteZeekConfigError( "Could not locate {}".format(self.install_directory)) except Exception as e: raise zeek_exceptions.WriteZeekConfigError( "General error while attempting to write new node.cfg file to {}; {}" .format(self.install_directory, e))
class _ArtifactoryCached: """Artifactory Local Cached Repository""" def __init__(self, arti_url=''): self._conf = ConfigParser() self._conf_file = join(ARTI_LOCAL_REPO, 'config') self._section = arti_url or 'localhost' if not exists(self._conf_file): if not exists(dirname(self._conf_file)): os.mkdir(dirname(self._conf_file)) else: self._conf.read(self._conf_file) # add section if not self._conf.has_section(self._section): self._conf.add_section(self._section) # rewrite config self._conf.write(open(self._conf_file, 'w')) def refresh(self, file_path='', file_local=''): self._conf.read(self._conf_file) self._conf.set(self._section, _revert_path(file_path), file_local) self._conf.write(open(self._conf_file, 'w')) def fetch(self, file_path, md5_str): """return (old, new)""" self._conf.read(self._conf_file) try: _local_path = self._conf.get(self._section, _revert_path(file_path)) if not _local_path: return (None, None) if not exists(_local_path): return (None, None) if _checksum_md5(_local_path) != md5_str: return (_local_path, None) return (None, _local_path) except Exception: return (None, None)
def write_config_file(settings, file_obj): """Save settings into file.""" default_settings = Settings() parser = ConfigParser() core_section = 'macman' default_section = 'default' # Internal options. # Order internal options alphabetically so that output is repeatable and # predictable. core_options = [] for option in ['directory']: value = getattr(settings, option) is_default = False try: default_value = getattr(default_settings, option) except AttributeError: pass else: if default_value == value: is_default = True if not is_default: core_options.append(option, value) if core_options: parser.add_section(core_section) for option, value in core_options: parser.set(core_section, option, value) # Default options. default_options = [] options = settings.default.keys() options.sort() for option in options: value = settings.default[option] is_default = False try: default_value = default_settings.default[option] except KeyError: pass else: if default_value == value: is_default = True if not is_default: default_options.append(option, value) if default_options: parser.add_section(default_section) for option, value in default_options: parser.set(default_section, option, value) # VM options. vm_ids = settings.vms.keys() vm_ids.sort() for vm in vm_ids: parser.add_section(vm) options = settings.vms[vm].keys() options.sort() for option in options: parser.set(vm, option, settings.vms[vm][option]) # Write the file. parser.write(file_obj)
def _upload_credentials(aws_config, manager_config_path): __, temp_config = tempfile.mkstemp() 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) with open(temp_config, 'w') as temp_config_file: credentials.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 _generate_config_file(self, config_type): """Generate Boto cfg file and return its path """ __, config_path = tempfile.mkstemp() config = ConfigParser() config_schema = constants.BOTO_CONFIG_SCHEMA for section in config_schema: config.add_section(section) for key in config_schema[section]: config.set(section, key, key) if config_type == "invalid_option": config.set("Boto", "invalid_option", "foo") config.set("Credentials", "invalid_option2", "foo") if config_type == "invalid_section": config.add_section("invalid_section1") config.add_section("invalid_section2") with open(config_path, 'w') as config_file: config.write(config_file) return config_path
def save_selection(platform=None, device=None): """" Stores a platform/device selection to disk. Both platform and device are identified by their names. """ # Make sure platform and device can be stored as ascii if platform: platform = platform.encode('ascii').decode('ascii') if device: device = device.encode('ascii').decode('ascii') # Create configuration config = ConfigParser() config.add_section('selection') if platform: config.set('selection', 'platform', platform) if device: config.set('selection', 'device', device) # Write configuration to ini file inifile = os.path.expanduser(SETTINGS_FILE) with open(inifile, 'w') as configfile: config.write(configfile)
def read_config(): """ Read the oci-utils config files; read all files present in /etc/oci-utils.conf.d in order and populate a configParser instance. If no configuration file is found the default values are used. See __oci_utils_defaults. Returns ------- [ConfigParser] The oci_utils configuration. """ global oci_utils_config if oci_utils_config is not None: return oci_utils_config oci_utils_config = ConfigParser() # assign default oci_utils_config.add_section('auth') oci_utils_config.set('auth', 'auth_method', 'auto') oci_utils_config.set('auth', 'oci_sdk_user', 'opc') oci_utils_config.add_section('iscsi') oci_utils_config.set('iscsi', 'enabled', 'true') oci_utils_config.set('iscsi', 'scan_interval', '60') oci_utils_config.set('iscsi', 'max_volumes', '8') oci_utils_config.set('iscsi', 'auto_resize', 'true') oci_utils_config.set('iscsi', 'auto_detach', 'true') oci_utils_config.set('iscsi', 'detach_retry', '5') oci_utils_config.add_section('vnic') oci_utils_config.set('vnic', 'enabled', 'true') oci_utils_config.set('vnic', 'scan_interval', '60') oci_utils_config.set('vnic', 'vf_net', 'false') oci_utils_config.add_section('public_ip') oci_utils_config.set('public_ip', 'enabled', 'true') oci_utils_config.set('public_ip', 'refresh_interval', '600') if not os.path.exists(__oci_utils_conf_d): return oci_utils_config conffiles = [ os.path.join(__oci_utils_conf_d, f) for f in os.listdir(__oci_utils_conf_d) if os.path.isfile(os.path.join(__oci_utils_conf_d, f)) ] oci_utils_config.read(conffiles) return oci_utils_config