def init(self): #global SERVER_NAME, WORKNAME_NAME global WORKNAME_NAME """ 办理工人注册 """ #srv_name = config.CONFIG['server']['server_name'] wk_name = config.CONFIG['server']['worker_name'] """检测配置文件 if srv_name: SERVER_NAME = srv_name else: config.write('server', 'server_name', SERVER_NAME) """ if wk_name: WORKNAME_NAME = wk_name reg_list = get_reg_list() wk_info = reg_list.get(WORKNAME_NAME) if wk_info and wk_info['sysinfo']['ip'] == LOCAL_IP: return WORKNAME_NAME = sum(map(lambda n:int(n),LOCAL_IP)) config.write('server','worker_name',WORKNAME_NAME) # 报告机器状态 self.report(self.login_time) # 记录系统日志 system_log = get_system_log_queue() system_log.push(dict( host=LOCAL_IP, name=WORKNAME_NAME, type='power', timestamp=self.login_time)) #注册在线标识 set_online(WORKNAME_NAME)
def closeEvent(self, event): """Called when QWeeChat window is closed.""" self.network.disconnect_weechat() if self.debug_dialog: self.debug_dialog.close() config.write(self.config) QtGui.QMainWindow.closeEvent(self, event)
def save(): output = "" output = output + render_template('header.html') #output = output+ '<div id="content">' output = output + "<h1>Saving new configuration...</h1>" additionalLightingDuration = request.args.get('additionalLightingDuration') checkSensorsInterval = request.args.get('checkSensorsInterval') criticalHumidity = request.args.get('criticalHumidity') criticalBrightness = request.args.get('criticalBrightness') if additionalLightingDuration and checkSensorsInterval and criticalHumidity and criticalBrightness: config = ConfigParser() config.read('userproperties.ini') config.set('IntelligenterBlumentopf', 'additionalLightingDuration', additionalLightingDuration) config.set('IntelligenterBlumentopf', 'checkSensorsInterval', checkSensorsInterval) config.set('IntelligenterBlumentopf', 'criticalHumidity', criticalHumidity) config.set('IntelligenterBlumentopf', 'criticalBrightness', criticalBrightness) with open('userproperties.ini', 'w') as configfile: config.write(configfile) output = output + "<p>Successful. Please reboot</p>" output = output + '<br><form method="get" action="/reboot"><button type="submit">Reboot!</button></form>' else: output = output + "<p>Failed: Configuration values are invalid.</p>" output = output + '</div></body></html>' return output
def importItunes(self, path): config = configobj.ConfigObj(config_file) config['General']['path_to_xml'] = path config.write() import itunesimport itunesimport.itunesImport(path) raise cherrypy.HTTPRedirect("/")
def UpdateSettings(self, handler, query): config.reset() for section in ['Server', '_tivo_SD', '_tivo_HD', '_tivo_4K']: self.each_section(query, section, section) sections = query['Section_Map'][0].split(']')[:-1] for section in sections: ID, name = section.split('|') if query[ID][0] == 'Delete_Me': config.config.remove_section(name) continue if query[ID][0] != name: config.config.remove_section(name) config.config.add_section(query[ID][0]) self.each_section(query, ID, query[ID][0]) if query['new_Section'][0] != ' ': config.config.add_section(query['new_Section'][0]) config.write() if getattr(sys, 'frozen', False): if sys.platform == "win32": tivomak_path = os.path.join(os.path.dirname(sys.executable), 'dshow', 'tivomak') tmakcmd = [ tivomak_path, '-set', config.config.get('Server', 'tivo_mak') ] subprocess.Popen(tmakcmd, shell=True) handler.redir(SETTINGS_MSG, 5)
def receive_config(message): logging.debug(u'Receiving config file') #nombre = message.text.split(' ')[1] with open(u'.config', u'wb') as config: config.write(download_document(message)) logging.info(u'Config received') reply(message, u'Config received')
def refresh(count_list,list_array,filename): tmp_list = count_list[list_array:] config=open(str(filename)+'asid_list.txt','w') config.write('') config=open(str(filename)+'asid_list.txt','a') for i in tmp_list: config.write(i)
def closeWindow(): dsf1.destroy() available = int(config.parser.items("Levels")[0][1]) if available == self.current_level: config.parser.set("Levels", "available", str(available + 1)) config.write() self.closeLevel()
def __init__(self, *args, **kwargs): super(GlobalPlugin, self).__init__(*args, **kwargs) self.local_machine = local_machine.LocalMachine() self.slave_session = None self.master_session = None self.create_menu() self.connector = None self.control_connector_thread = None self.control_connector = None self.server = None self.hook_thread = None self.sending_keys = False self.key_modified = False self.sd_server = None cs = get_config()['controlserver'] if cs['autoconnect']: if cs['autoconnect'] == 1: # self-hosted server self.server = server.Server(SERVER_PORT, cs['key']) server_thread = threading.Thread(target=self.server.run) server_thread.daemon = True server_thread.start() address = address_to_hostport('localhost') elif cs['autoconnect'] == '2': address = address_to_hostport(cs['host']) elif cs['autoconnect'] == True: # Previous version config, change value to 2 for external control server config = get_config() config['controlserver']['autoconnect'] = 2 config.write() address = address_to_hostport(cs['host']) self.connect_control(address, cs['key']) # Connect to the server self.temp_location = os.path.join(shlobj.SHGetFolderPath(0, shlobj.CSIDL_COMMON_APPDATA), 'temp') self.ipc_file = os.path.join(self.temp_location, 'remote.ipc') self.sd_focused = False self.check_secure_desktop()
def update(args): try: config.write(args.config) print("update") #gui.main(args) except ImportError as e: LOG.error(str(e))
def SaveNPL(self, handler, query): config = ConfigParser.ConfigParser() config.read(config_file_path) if 'tivo_mak' in query: config.set(query['Container'][0], 'tivo_mak', query['tivo_mak'][0]) if 'togo_path' in query: config.set(query['Container'][0], 'togo_path', query['togo_path'][0]) f = open(config_file_path, "w") config.write(f) f.close() subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template( file=os.path.join(SCRIPTDIR, 'templates', 'redirect.tmpl')) t.container = cname t.time = '2' t.url = '/TiVoConnect?last_page=NPL&Command=Reset&Container=' + cname t.text = '<h3>Your Settings have been saved.</h3> <br>You settings have been saved to the pyTivo.conf file.'+\ 'pyTivo will now do a <b>Soft Reset</b> to allow these changes to take effect.'+\ '<br> The <a href="/TiVoConnect?last_page=NPL&Command=Reset&Container='+ cname +'"> Reset</a> will occur in 2 seconds.' handler.wfile.write(t)
def musicScan(self, path): config = configobj.ConfigObj(config_file) config['General']['path_to_itunes'] = path config.write() import itunesimport itunesimport.scanMusic(path) raise cherrypy.HTTPRedirect("home")
def bootup(): version = "1.1" parse = argparse.ArgumentParser(description = 'makeswordclouds') parse.add_argument('-l', '--login', action = 'store_true', help = 'Login to a different account than config account') args = parse.parse_args() print('\nMWC // version ' + version) print('------------------') if not os.path.isfile(config_name) or not os.path.isfile(replied_name): config.write(current, config_name) config.write(replied_current, replied_name) print('> Created config.json & replied.json. Please edit the values in the config before continuing.') sys.exit() conf = config.load(config_name) if conf['limit'] == '': print('> The limit in the config is not set! Please set it to a proper number.') sys.exit() elif int(conf['limit']) > 200: print('> The limit in the config is over 200! Please make it a lower number.') sys.exit() if conf['id'] == '': print('> The id in the config is not set! Please set it to an Imgur client id.') sys.exit() user = conf['credentials']['username'] passwd = conf['credentials']['password'] current['credentials']['username'] = user current['credentials']['password'] = passwd current['limit'] = conf['limit'] current['id'] = conf['id'] if args.login or user == "" or passwd == "": user = raw_input('> Reddit username: '******'s password: " % user) print agent = ( '/u/' + user + ' running makeswordclouds, version ' + version + ', created by /u/WinneonSword.' ) r = praw.Reddit(user_agent = agent) utils = Utils(conf, r) reddit.login(user, passwd, r) loop(user, r, utils)
def loop(user, reddit, utils): print('\n> Booting up makeswordclouds. You will be notified when makeswordclouds detects a broken link.') print('> To stop the bot, press Ctrl + C.') try: while True: print('\n> Checking submissions for valid entries...') submissions = reddit.get_subreddit('all').get_hot(limit = 100) for submission in submissions: if submission.id not in utils.replied and submission.num_comments >= 50: print('\n> Found valid submission in the subreddit /r/' + submission.subreddit.display_name + '!') text = utils.get_submission_comments(submission.id) cloud = utils.make_cloud(text) upload = utils.upload_image(cloud) print('> Successfully made word cloud and uploaded to imgur!') os.remove(cloud) try: reply = ( 'Here is a word cloud of all of the comments in this thread: ' + upload + '\n\n' '*****\n' '[^source ^code](https://github.com/WinneonSword/makeswordclouds) ^| [^contact ^developer](http://reddit.com/user/WinneonSword)' ) utils.handle_rate_limit(submission, reply) print('> Comment posted! Link: ' + upload) utils.replied.add(submission.id) listt = list(utils.replied) replied_current['replied'] = listt config.write(replied_current, utils.replied_file) except: print('> Failed to post comment.') traceback.print_exc(file = sys.stdout) print('\n> Sleeping.') time.sleep(15) except KeyboardInterrupt: print('> Stopped makeswordclouds. Thank you for running this bot!') except: print('\n> An error has occured. Restarting the bot.') traceback.print_exc(file = sys.stdout) loop(user, reddit, utils)
def do_remove(self, subcmd, opts, apps): """${cmd_name}: Removes comma-separated list of apps to the tracker ${cmd_usage} """ for a in apps.split(","): self.config_dict['apps']['whitelist'].discard(a) config.write(app.CONFIG_FILEPATH, self.config_dict)
def update_config(LastUpdateDate): print(f'{bcolors.HEADER}Start update_config') config = configparser.ConfigParser() config.read(_file_locald_ini) config.set("Settings", "LastUpdateDate", str(LastUpdateDate)) with open(_file_locald_ini, "w") as config_file: config.write(config_file) print(f'{bcolors.OKGREEN}update_config = {_file_locald_ini},{config_file}')
def quit(*args): pygame.quit() print "Saving configuration." config.unlock("unlocker") if int(config.get("scores-versus-3", "1").split(",")[1]) > 20000: config.unlock("single") config.write(file(rc_file, "w")) raise SystemExit
def add_banned_subreddit(self, subreddit): if subreddit not in self.banned: self.banned.add(subreddit) current['banned'] = list(self.banned) config.write(current, self.config_file)
def saveResult(result): config = ConfigParser.ConfigParser() config.add_section('Result') config.set('Result', 'moments', "\n"+"\n".join(map(lambda arg: " ".join(map(str, arg)), result['moments']))) config.set('Result', 'density', "\n"+"\n".join(map(lambda arg: " ".join(map(str, arg)), result['density']))) config.set('Result', 'bprob', " ".join(map(str, result['bprob']))) config.set('Result', 'mpost', " ".join(map(str, result['mpost']))) configfile = open(options['save'], 'wb') config.write(configfile)
def _save_settings(self): self.settings["relay"]["server"] = self.entry1.get_text() self.settings["relay"]["port"] = self.entry2.get_text() self.settings["relay"]["password"] = self.entry3.get_text() self.settings["relay"]["ssl"] = "on" if self.switch1.get_active() else "off" self.settings["relay"]["autoconnect"] = "on" if self.switch2.get_active( ) else "off" config.write(self.settings) self.hide()
def send_command(command): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: client.connect((HOST, PORT)) except: return False write(client, command) res = read(client) client.close() return res if res else "not implemented"
def save_settings(): disconnect() port_iter = GtkComboBox_ports.get_active_iter() if port_iter is not None: ports_model = GtkComboBox_ports.get_model() selected_port = ports_model.get_value(port_iter, 0) config.write(Port=selected_port, Filename=GtkEntry_file.get_text()) port = selected_port filename = GtkEntry_file.get_text() load_history() connect(port)
def OnKeyPressed(self, event): if self.edit_btn is None: return try: code = event.GetKeyCode() char = str(unichr(event.GetUniChar())).lower() if code in [375, 331]: key = "7" elif code in [377, 332]: key = "8" elif code in [380, 333]: key = "9" elif code in [376, 328]: key = "4" elif code in [383, 329]: key = "5" elif code in [378, 330]: key = "6" elif code in [382, 325]: key = "1" elif code in [379, 326]: key = "2" elif code in [382, 327]: key = "3" elif not char.isalnum(): self.ResetButtons() return else: key = char except: return self.edit_btn.SetLabel(key.upper()) self.UpdateKeys() config.parser.set("Controls", self.function, ",".join(self.keys)) config.write() self.GetParent().UpdateButtons() self.edit_btn = None
def _storeStageCloseProps(nexusApi, build_cfg, repoId, snapshot_url): status = nexusApi.getrepositorystatus(repoId) config = ConfigParser.ConfigParser() config.add_section('stageclose') config.set('stageclose', 'staging.repo.url', status['repositoryURI']) config.set('stageclose', 'staging.repo.id', repoId) config.set('stageclose', 'git.repo', snapshot_url.split('@')[0]) config.set('stageclose', 'git.treeish', snapshot_url.split('@')[1]) with open(build_cfg.close_stage_props_file(), 'w') as f: config.write(f)
def UpdateSettings(self, handler, query): config.reset() for section in ['Server', '_tivo_SD', '_tivo_HD']: new_setting = new_value = ' ' for key in query: if key.startswith('opts.'): data = query[key] del query[key] key = key[5:] query[key] = data if key.startswith(section + '.'): _, option = key.split('.') if not config.config.has_section(section): config.config.add_section(section) if option == 'new__setting': new_setting = query[key][0] elif option == 'new__value': new_value = query[key][0] elif query[key][0] == ' ': config.config.remove_option(section, option) else: config.config.set(section, option, query[key][0]) if not(new_setting == ' ' and new_value == ' '): config.config.set(section, new_setting, new_value) sections = query['Section_Map'][0].split(']') sections.pop() # last item is junk for section in sections: ID, name = section.split('|') if query[ID][0] == 'Delete_Me': config.config.remove_section(name) continue if query[ID][0] != name: config.config.remove_section(name) config.config.add_section(query[ID][0]) for key in query: if key.startswith(ID + '.'): _, option = key.split('.') if option == 'new__setting': new_setting = query[key][0] elif option == 'new__value': new_value = query[key][0] elif query[key][0] == ' ': config.config.remove_option(query[ID][0], option) else: config.config.set(query[ID][0], option, query[key][0]) if not(new_setting == ' ' and new_value == ' '): config.config.set(query[ID][0], new_setting, new_value) if query['new_Section'][0] != ' ': config.config.add_section(query['new_Section'][0]) config.write() handler.redir(SETTINGS_MSG, 5)
def UpdateSettings(self, handler, query): config.reset() for section in ['Server', '_tivo_SD', '_tivo_HD']: new_setting = new_value = ' ' for key in query: if key.startswith('opts.'): data = query[key] del query[key] key = key[5:] query[key] = data if key.startswith(section + '.'): _, option = key.split('.') if not config.config.has_section(section): config.config.add_section(section) if option == 'new__setting': new_setting = query[key][0] elif option == 'new__value': new_value = query[key][0] elif query[key][0] == ' ': config.config.remove_option(section, option) else: config.config.set(section, option, query[key][0]) if not (new_setting == ' ' and new_value == ' '): config.config.set(section, new_setting, new_value) sections = query['Section_Map'][0].split(']') sections.pop() # last item is junk for section in sections: ID, name = section.split('|') if query[ID][0] == 'Delete_Me': config.config.remove_section(name) continue if query[ID][0] != name: config.config.remove_section(name) config.config.add_section(query[ID][0]) for key in query: if key.startswith(ID + '.'): _, option = key.split('.') if option == 'new__setting': new_setting = query[key][0] elif option == 'new__value': new_value = query[key][0] elif query[key][0] == ' ': config.config.remove_option(query[ID][0], option) else: config.config.set(query[ID][0], option, query[key][0]) if not (new_setting == ' ' and new_value == ' '): config.config.set(query[ID][0], new_setting, new_value) if query['new_Section'][0] != ' ': config.config.add_section(query['new_Section'][0]) config.write() handler.redir(SETTINGS_MSG, 5)
def update_config(section, variable, value): """Update the config with the new value for the variable. If dangermode is on, we save them to config.ini, else we write them to the temporary dictionary """ if conf["atm"]["dangermode"].lower() == "on": config = create_config() config[section][variable] = value with open(CONFIG_FILE, "w") as configfile: config.write(configfile) else: conf[section][variable] = value
async def db_commit_wait(self, ctx, *args): """[ADMIN] Gets/sets the number of game ticks between database commits.""" msg = '' if len(args) == 0: msg = 'DB commit wait is {} ticks.'.format( self._config.db_commit_wait) else: self._config.db_commit_wait = args[0] config.write(self._config) msg = 'DB commit wait set to {} ticks.'.format( self._config.db_commit_wait) await discord_output.private(self._bot, ctx.message.author, msg)
def closeEvent(self, event): """Called when QWeeChat window is closed.""" if self.config.getboolean("notifications", "close_to_tray"): self.hide() self.notifier.tray_icon.show() self.notifier.update(event) event.ignore() return self.network.disconnect_weechat() if self.debug_dialog: self.debug_dialog.close() config.write(self.config) QtGui.QMainWindow.closeEvent(self, event)
def prepare_remote(): logger.info("Preparing remote maschine") logger.debug("Local __main__ path: " + main_path) config.setstring("SERVICE_WORKING_DIR", main_path) config.write() transport = paramiko.Transport((CONFIG.REMOTE_HOST, 22)) transport.connect(username=credentials["user"], password=credentials["pass"]) logger.info("Connected to " + CONFIG.REMOTE_HOST) sftp = paramiko.SFTPClient.from_transport(transport) # remove files on remote maschine logger.info("Removing old files on remote machine") for fattr in sftp.listdir_attr(CONFIG.REMOTE_WORK_DIR): if (stat.S_ISREG(fattr.st_mode)): try: sftp.remove(os.path.join(CONFIG.REMOTE_WORK_DIR, fattr.filename)) except IOError: pass # create remote "common" directory if it does not exist try: sftp.mkdir(os.path.join(CONFIG.REMOTE_WORK_DIR, "common")) except IOError: pass # remove files from remote "common" directory for fattr in sftp.listdir_attr( os.path.join(CONFIG.REMOTE_WORK_DIR, "common")): if (stat.S_ISREG(fattr.st_mode)): try: sftp.remove(os.path.join( CONFIG.REMOTE_WORK_DIR, "common", fattr.filename)) except IOError: pass # put files on remote maschine logger.info("Uploading files to remote maschine") sftp.put(os.path.join(main_path, "config.py"), os.path.join(CONFIG.REMOTE_WORK_DIR, "config.py")) sftp.put(os.path.join(main_path, "config"), os.path.join(CONFIG.REMOTE_WORK_DIR, "config")) for fname in os.listdir(os.path.join(main_path, "remote")): sftp.put(os.path.join(main_path, "remote", fname), os.path.join(CONFIG.REMOTE_WORK_DIR, fname)) sftp.chmod(os.path.join(CONFIG.REMOTE_WORK_DIR, fname), 0775) for fname in os.listdir(os.path.join(main_path, "common")): sftp.put(os.path.join(main_path, "common", fname), os.path.join(CONFIG.REMOTE_WORK_DIR, "common", fname)) sftp.close() transport.close() logger.info("Remote maschine prepared")
def saveResult(result): config = ConfigParser.ConfigParser() config.add_section('Sampling Result') config.set('Sampling Result', 'counts', "\n"+"\n".join(map(lambda arg: " ".join(map(str, arg)), result['counts']))) config.set('Sampling Result', 'moments', "\n"+"\n".join(map(lambda arg: " ".join(map(str, arg)), result['moments']))) config.set('Sampling Result', 'density', "\n"+"\n".join(map(lambda arg: " ".join(map(str, arg)), result['density']))) config.set('Sampling Result', 'samples', " ".join(map(str, result['samples']))) config.set('Sampling Result', 'utility', " ".join(map(str, result['utility']))) config.set('Sampling Result', 'bprob', " ".join(map(str, result['bprob']))) config.set('Sampling Result', 'mpost', " ".join(map(str, result['mpost']))) config.set('Sampling Result', 'distances', " ".join(map(str, result['distances']))) config.set('Sampling Result', 'states', "\n".join(map(str, result['states']))) configfile = open(options['save'], 'wb') config.write(configfile) configfile.close()
def _save_and_close(self): for widget in (self.stacked_panes.widget(i) for i in range(self.stacked_panes.count())): for key, field in widget.fields.items(): if isinstance(field, QtGui.QComboBox): text = field.itemText(field.currentIndex()) data = field.itemData(field.currentIndex()) text = data if data else text elif isinstance(field, QtGui.QCheckBox): text = "on" if field.isChecked() else "off" else: text = field.text() self.config.set(widget.section_name, key, str(text)) config.write(self.config) self.parent.apply_preferences() self.close()
def save_config(self): if self.config is None: print("INFO: save_config() called but no config set") return print("Saving config") try: config.write(self.config) except IOError, e: print("ERR: could not update config: "+str(e)) dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Could not update config")) dialog.format_secondary_text(str(e)) dialog.run() dialog.destroy()
def save_config(self): if self.config is None: print("INFO: save_config() called but no config set") return print("Saving config") try: config.write(self.config) except IOError, e: print("ERR: could not update config: " + str(e)) dialog = Gtk.MessageDialog(self, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.OK, _("Could not update config")) dialog.format_secondary_text(str(e)) dialog.run() dialog.destroy()
def delete_extremity(self): config = ConfigParser() config.read('config.ini') for item in config.items('extremity'): if item[0] == self.extremityOption.get(): config.remove_option('extremity', item[0]) config.write(open('config.ini', 'w')) inputs = ConfigParser() inputs.read('current_inputs.ini') for item in inputs.items('extremity'): if item[0] == self.extremityOption.get(): inputs.remove_option('extremity', item[0]) inputs.write(open('current_inputs.ini', 'w')) self.removeExtremityWindow.destroy() self.profileWindow.destroy() self.profile_window() self.profileNotebook.select(1)
def add_extremity(self): config = ConfigParser() config.read('config.ini') config.set('extremity', self.addExtremityEntry.get(), '(0,0)+keypress+w') with open('config.ini', 'w') as f: config.write(f) inputs = ConfigParser() inputs.read('current_inputs.ini') inputs.set('extremity', self.addExtremityEntry.get(), '0') with open('current_inputs.ini', 'w') as f: inputs.write(f) self.addExtremityWindow.destroy() self.profileWindow.destroy() self.profile_window() self.profileNotebook.select(1)
def expander(delay): print('expander') for i in range(len(sections)): c = i - 1 device = config.get(sections[c], 'device') if device == 'expander': address = int(config.get(sections[c], 'address'), base=16) port = int(config.get(sections[c], 'port'), base=16) should = config.get(sections[c], 'should') value = config.get(sections[c], 'value') if should == value: print("None") else: set = bus_write(address, port, int(should, base=2)) if set == 1: config.set(sections[c], 'value', should) config.write() print("Done") time.sleep(delay)
def train_model(self): self.newCustomizedModel = train_customized_model.CustomizedModel( self.newCustomizedMotion.motionType) self.newCustomizedModel.train() config = ConfigParser() config.read('config.ini') config.set('customized', self.newCustomizedMotion.motionType, 'keypress+w') with open('config.ini', 'w') as f: config.write(f) inputs = ConfigParser() inputs.read('current_inputs.ini') inputs.set('customized', self.newCustomizedMotion.motionType, '0') with open('current_inputs.ini', 'w') as f: inputs.write(f) self.customizedMotionWindow.destroy() self.profileWindow.destroy() self.profile_window()
def UpdateSettings(self, handler, query): config.reset() for section in ['Server', '_tivo_SD', '_tivo_HD', '_tivo_4K']: self.each_section(query, section, section) sections = query['Section_Map'][0].split(']')[:-1] for section in sections: ID, name = section.split('|') if query[ID][0] == 'Delete_Me': config.config.remove_section(name) continue if query[ID][0] != name: config.config.remove_section(name) config.config.add_section(query[ID][0]) self.each_section(query, ID, query[ID][0]) if query['new_Section'][0] != ' ': config.config.add_section(query['new_Section'][0]) config.write() handler.redir(SETTINGS_MSG, 5)
def add_username_to_config_ini(username): config = SafeConfigParser() config.read('config.ini') if not config.has_section('main'): config.add_section('main') config.set('main', 'users', username) else: users = config.get('main', 'users') user_already_in_config = False for user in users.split(','): if user == username: user_already_in_config = True break if user_already_in_config is False: config.set('main', 'users', users + ',' + username) with open('config.ini', 'w') as f: config.write(f)
def setup(): # sections = list(config.sections()) #print(sections) # print(len(sections)) for i in range(len(sections)): c = i - 1 device = config.get(sections[c], 'device') # print(device) if device == 'expander': address = int(config.get(sections[c], 'address'), base=16) port = int(config.get(sections[c], 'port'), base=16) mode = int(config.get(sections[c], 'mode'), base=16) default = config.get(sections[c], 'default') bus_define(address, mode) set = bus_write(address, port, int(default, base=2)) if set == 1: config.set(sections[c], 'value', default) config.write() print("ok")
def do_init(self, subcmd, opts): """${cmd_name}: Initializes the local repository and settings ${cmd_usage} """ if not os.path.exists(app.CONFIG_FOLDER): os.makedirs(app.CONFIG_FOLDER) if not os.path.exists(app.CONFIG_FILEPATH): username = self.config_dict['core']['username'] while username == '': sys.stdout.write("Enter your prefered username: "******"username cannot be empty" self.config_dict['core']['username'] = username config.write(app.CONFIG_FILEPATH, self.config_dict) print "Settings initialized for <%s>" % username
def UpdateSettings(self, handler, query): config.reset() for section in ['Server', '_tivo_SD', '_tivo_HD']: self.each_section(query, section, section) sections = query['Section_Map'][0].split(']')[:-1] for section in sections: ID, name = section.split('|') if query[ID][0] == 'Delete_Me': config.config.remove_section(name) continue if query[ID][0] != name: config.config.remove_section(name) config.config.add_section(query[ID][0]) self.each_section(query, ID, query[ID][0]) if query['new_Section'][0] != ' ': config.config.add_section(query['new_Section'][0]) config.write() handler.redir(SETTINGS_MSG, 5)
def checkRequired(parsed): log.log(log.DEBUG, 'Checking required fields') if not 'doc-tag' in parsed: log.log(log.ERROR, 'No tag specified') return (1, 'No tag specified') tag = parsed['doc-tag'][0].split('-', 1) event_type = tag[0] if config.has_section('fields-' + event_type): items = config.items('fields-' + event_type) for i in items: if i[0] == 'required': required_fields = i[1].split(', ') for field in required_fields: if not field in parsed: log.log(log.ERROR, 'Required field "' + field + '" is missing') return (1, 'Required field "' + field + '" is missing') elif i[0] == 'optional': return (0, '') #optional_fields = i[1].split(', ') #for field in optional_fields: # if field in parsed: # pass else: log.log(log.ERROR, 'Unknown definition in config: ' + repr(i)) return (1, 'Unknown definition in config: ' + repr(i)) else: log.log(log.ERROR, 'Event type not specified in config file. Adding section. All fields will be added as optional. Fix this soon.') config.add_section('fields-' + event_type) oldkey = '' for key in parsed: if oldkey == '': newkey = key else: newkey = oldkey + ', ' + key config.set('fields-' + event_type, 'optional', newkey) oldkey = config.get('fields-' + event_type, 'optional') config.write() return (0, '')
def init(self): #global SERVER_NAME, WORKNAME_NAME """ 办理工人注册 """ #srv_name = config.CONFIG['server']['server_name'] wk_name = config.CONFIG['server']['worker_name'] """检测配置文件 if srv_name: SERVER_NAME = srv_name else: config.write('server', 'server_name', SERVER_NAME) """ if wk_name: global_list.WORKNAME_NAME = wk_name reg_list = get_reg_list() wk_info = reg_list.get(global_list.WORKNAME_NAME) if wk_info and wk_info['sysinfo']['ip'] == global_list.LOCAL_IP: return #global_list.WORKNAME_NAME = str(sum(map(lambda n:int(n),global_list.LOCAL_IP.split('.')))) global_list.WORKNAME_NAME = utils.get_mac() config.write('server','worker_name',global_list.WORKNAME_NAME) #合并线上配置 reg_list = get_reg_list() wk_info = reg_list.get(global_list.WORKNAME_NAME) if wk_info and 'doing' in wk_info and wk_info['doing']: for k,task in wk_info['doing'].items(): if int(task['status']) < 3: get_task_queue(global_list.WORKNAME_NAME).push(task) # 报告机器状态 self.report(self.login_time) # 记录系统日志 system_log = get_system_log_queue() system_log.push(dict( host=global_list.LOCAL_IP, name=global_list.WORKNAME_NAME, type='power', timestamp=self.login_time)) #注册在线标识 set_online(global_list.WORKNAME_NAME)
def delete_customized_exercise(self): config = ConfigParser() config.read('config.ini') for item in config.items('customized'): if item[0] == self.customizedExercisesOption.get(): config.remove_option('customized', item[0]) config.write(open('config.ini', 'w')) inputs = ConfigParser() inputs.read('current_inputs.ini') for item in inputs.items('customized'): print(item[0]) if item[0] == self.customizedExercisesOption.get(): inputs.remove_option('customized', item[0]) inputs.write(open('current_inputs.ini', 'w')) dirpath = "models/customized/" + self.customizedExercisesOption.get() if os.path.exists(dirpath) and os.path.isdir(dirpath): shutil.rmtree(dirpath) self.removeCustomizedMotionWindow.destroy() self.profileWindow.destroy() self.profile_window()
def SaveNPL(self, handler, query): config = ConfigParser.ConfigParser() config.read(config_file_path) if 'tivo_mak' in query: config.set(query['Container'][0], 'tivo_mak', query['tivo_mak'][0]) if 'togo_path' in query: config.set(query['Container'][0], 'togo_path', query['togo_path'][0]) f = open(config_file_path, "w") config.write(f) f.close() subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template(file=os.path.join(SCRIPTDIR,'templates', 'redirect.tmpl')) t.container = cname t.time = '2' t.url = '/TiVoConnect?last_page=NPL&Command=Reset&Container=' + cname t.text = '<h3>Your Settings have been saved.</h3> <br>You settings have been saved to the pyTivo.conf file.'+\ 'pyTivo will now do a <b>Soft Reset</b> to allow these changes to take effect.'+\ '<br> The <a href="/TiVoConnect?last_page=NPL&Command=Reset&Container='+ cname +'"> Reset</a> will occur in 2 seconds.' handler.wfile.write(t)
def __init__(self, *args, **kwargs): super(GlobalPlugin, self).__init__(*args, **kwargs) self.local_machine = local_machine.LocalMachine() self.slave_session = None self.master_session = None self.create_menu() self.connector = None self.control_connector_thread = None self.control_connector = None self.server = None self.hook_thread = None self.sending_keys = False self.key_modified = False self.sd_server = None cs = get_config()['controlserver'] if cs['autoconnect']: if cs['autoconnect'] == 1: # self-hosted server self.server = server.Server(SERVER_PORT, cs['key']) server_thread = threading.Thread(target=self.server.run) server_thread.daemon = True server_thread.start() address = address_to_hostport('localhost') elif cs['autoconnect'] == '2': address = address_to_hostport(cs['host']) elif cs['autoconnect'] == True: # Previous version config, change value to 2 for external control server config = get_config() config['controlserver']['autoconnect'] = 2 config.write() address = address_to_hostport(cs['host']) self.connect_control(address, cs['key']) # Connect to the server self.temp_location = os.path.join( shlobj.SHGetFolderPath(0, shlobj.CSIDL_COMMON_APPDATA), 'temp') self.ipc_file = os.path.join(self.temp_location, 'remote.ipc') self.sd_focused = False self.check_secure_desktop()
def UpdateSettings(self, handler, query): config = ConfigParser.ConfigParser() config.read(config_file_path) for key in query: if key.startswith('Server.'): section, option = key.split('.') if option == "new__setting": new_setting = query[key][0] continue if option == "new__value": new_value = query[key][0] continue if query[key][0] == " ": config.remove_option(section, option) else: config.set(section, option, query[key][0]) if not(new_setting == ' ' and new_value == ' '): config.set('Server', new_setting, new_value) sections = query['Section_Map'][0].split(']') sections.pop() #last item is junk for section in sections: ID, name = section.split('|') if query[ID][0] == "Delete_Me": config.remove_section(name) continue if query[ID][0] != name: config.remove_section(name) config.add_section(query[ID][0]) for key in query: if key.startswith(ID + '.'): junk, option = key.split('.') if option == "new__setting": new_setting = query[key][0] continue if option == "new__value": new_value = query[key][0] continue if query[key][0] == " ": config.remove_option(query[ID][0], option) else: config.set(query[ID][0], option, query[key][0]) if not(new_setting == ' ' and new_value == ' '): config.set(query[ID][0], new_setting, new_value) if query['new_Section'][0] != " ": config.add_section(query['new_Section'][0]) f = open(config_file_path, "w") config.write(f) f.close() subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template(file=os.path.join(SCRIPTDIR,'templates', 'redirect.tmpl')) t.container = cname t.time = '10' t.url = '/TiVoConnect?Command=Admin&Container=' + cname t.text = '<h3>Your Settings have been saved.</h3> <br>You settings have been saved to the pyTivo.conf file.'+\ 'However you will need to do a <b>Soft Reset</b> before these changes will take effect.'+\ '<br> The <a href="/TiVoConnect?Command=Admin&Container='+ cname +'"> Admin</a> page will reload in 10 seconds.' handler.wfile.write(t)
def saveProjectOf(self, projFile): config.write(open(projFile, "w"), config.qtGetter, self.projectinfo) self.dirty = False return
def add_replied_submission(self, id): self.replied.add(id) replied_current['replied'] = list(self.replied) config.write(replied_current, self.replied_file)
def config_set(self, section, option, value): self.config.set(section, option, value) self.apply_preferences() config.write(self.config)
def save_project(self,catchment_obj,project_filename): ''' Saves the contents of the catchment object and gui object to a project archive :param catchment,filename :type catchment object,string,gui data object :return: None :rtype: None ''' print(project_filename) fname = os.path.basename(project_filename).split('.')[0] tempdir = os.path.join(os.path.split(project_filename)[0],fname) if os.path.isdir(tempdir) is False: os.makedirs(tempdir) else: print("Temp directory exists, exiting") config = ConfigObj() config.filename = os.path.join(tempdir,fname+".ini") config['Software'] = 'Statistical Flood Estimation Tool, Open Hydrology' config['Version'] = '0.0.2' config['Date saved'] = ctime() config['User']= environ['USERNAME'] config['Catchment_name'] = catchment_obj config['File paths']={} config['File paths']['ini_file'] = fname+".ini" cdsFile = os.path.join(tempdir,fname+".cd3") config['File paths']['cds_file'] = fname+".cd3" write_cds_file(catchment_obj,cdsFile) if len(catchment_obj.amax_records) != 0: amFile = os.path.join(tempdir,fname+".am") config['File paths']['am_file'] = fname+".am" write_am_file(catchment_obj,amFile) else: config['File paths']['am_file']=None if catchment_obj is None: config['File paths']['pot_file'] = fname+".pt" else: config['File paths']['pot_file'] = None config['File paths']['markdown_analysis_report']=None config['File paths']['checksum'] = None config['Supplementary information']={} config['Supplementary information']['catchment']=str(self.page1.catchment.GetValue()) config['Supplementary information']['location']=str(self.page1.location.GetValue()) config['Supplementary information']['purpose']=str(self.page1.purpose.GetValue()) config['Supplementary information']['authors_notes']=str(self.page1.author_notes.GetValue()) config['Supplementary information']['author_signature']=str(self.page1.author_signature.GetValue()) config['Supplementary information']['checkers_notes']=str(self.page1.checkers_notes.GetValue()) config['Supplementary information']['checker_signature']=str(self.page1.checker_signature.GetValue()) config['Supplementary information']['cds_notes'] = self.page2.cds_notes.GetValue() config['Analysis']={} config['Analysis']['qmed']={} config['Analysis']['qmed']['comment']=self.page3.qmed_notes.GetValue() config['Analysis']['qmed']['user_supplied_qmed'] = self.page3.qmed_user.GetValue() config['Analysis']['qmed']['estimate_method']=self.page3.qmed_method config['Analysis']['qmed']['donor_station_limit']=self.page3.station_limit.GetValue() config['Analysis']['qmed']['donor_search_limit']=self.page3.station_search_distance.GetValue() config['Analysis']['qmed']['donor_method']='default' config['Analysis']['qmed']['idw_weight']=self.page3.idw_weight.GetValue() config['Analysis']['qmed']['adopted_donors']=self.page3.adopted_donors config['Analysis']['qmed']['keep_rural']=self.page3.keep_rural config['Analysis']['qmed']['urban_method']='default' config['Analysis']['fgc']={} config['Analysis']['fgc']['comment']='' config['Analysis']['fgc']['adopted']='fgc1' config['Analysis']['fgc']['fgc1']={} config['Analysis']['fgc']['fgc1']['comment']='' config['Analysis']['fgc']['fgc1']['method']='pooling' config['Analysis']['fgc']['fgc1']['pooling_group']=[1001,1002] config['Analysis']['fgc']['fgc1']['weighting_method']='default' config['Analysis']['fgc']['fgc2']={} config['Analysis']['fgc']['fgc2']['comment']='' config['Analysis']['fgc']['fgc2']['method']='fssr14' config['Analysis']['fgc']['fgc2']['hydrological_region']=1 config.write() if os.path.splitext(project_filename)[1] =='.hyd': zipToArchive(tempdir,project_filename)
def UpdateSettings(self, handler, query): config = ConfigParser.ConfigParser() config.read(config_file_path) for key in query: if key.startswith('Server.'): section, option = key.split('.') if option == "new__setting": new_setting = query[key][0] continue if option == "new__value": new_value = query[key][0] continue if query[key][0] == " ": config.remove_option(section, option) else: config.set(section, option, query[key][0]) if not (new_setting == ' ' and new_value == ' '): config.set('Server', new_setting, new_value) sections = query['Section_Map'][0].split(']') sections.pop() #last item is junk for section in sections: ID, name = section.split('|') if query[ID][0] == "Delete_Me": config.remove_section(name) continue if query[ID][0] != name: config.remove_section(name) config.add_section(query[ID][0]) for key in query: if key.startswith(ID + '.'): junk, option = key.split('.') if option == "new__setting": new_setting = query[key][0] continue if option == "new__value": new_value = query[key][0] continue if query[key][0] == " ": config.remove_option(query[ID][0], option) else: config.set(query[ID][0], option, query[key][0]) if not (new_setting == ' ' and new_value == ' '): config.set(query[ID][0], new_setting, new_value) if query['new_Section'][0] != " ": config.add_section(query['new_Section'][0]) f = open(config_file_path, "w") config.write(f) f.close() subcname = query['Container'][0] cname = subcname.split('/')[0] handler.send_response(200) handler.end_headers() t = Template( file=os.path.join(SCRIPTDIR, 'templates', 'redirect.tmpl')) t.container = cname t.time = '10' t.url = '/TiVoConnect?Command=Admin&Container=' + cname t.text = '<h3>Your Settings have been saved.</h3> <br>You settings have been saved to the pyTivo.conf file.'+\ 'However you will need to do a <b>Soft Reset</b> before these changes will take effect.'+\ '<br> The <a href="/TiVoConnect?Command=Admin&Container='+ cname +'"> Admin</a> page will reload in 10 seconds.' handler.wfile.write(t)
def init(args): if not os.path.exists(args.config): config.write(args.config) else: raise RuntimeError("{0} already exists".format(args.config))
def main(): p = OptionParser(usage="usage: %prog [options] [name] [version]", description=__doc__) p.add_option("--config", action="store_true", help="display the configuration and exit") p.add_option('-f', "--force", action="store_true", help="force install the main package " "(not it's dependencies, see --forceall)") p.add_option("--forceall", action="store_true", help="force install of all packages " "(i.e. including dependencies)") p.add_option('-i', "--info", action="store_true", help="show information about a package") p.add_option('-l', "--list", action="store_true", help="list the packages currently installed on the system") p.add_option('-n', "--dry-run", action="store_true", help="show what would have been downloaded/removed/installed") p.add_option('-N', "--no-deps", action="store_true", help="neither download nor install dependencies") p.add_option("--remove", action="store_true", help="remove a package") p.add_option('-s', "--search", action="store_true", help="search the index in the repo (chain) of packages " "and display versions available.") p.add_option('-v', "--verbose", action="store_true") p.add_option('--version', action="store_true") p.add_option("--whats-new", action="store_true", help="display to which installed packages updates are " "available") opts, args = p.parse_args() if len(args) > 0 and opts.config: p.error("Option takes no arguments") if opts.force and opts.forceall: p.error("Options --force and --forceall exclude each ohter") pat = None if (opts.list or opts.search) and args: pat = re.compile(args[0], re.I) if opts.version: # --version from enstaller import __version__ print "IronPkg version:", __version__ return if opts.config: # --config config.print_config() return if config.get_path() is None: # create config file if it dosn't exist config.write() conf = config.read() # conf global dry_run, version # set globals dry_run = opts.dry_run version = opts.version if opts.list: # --list print_installed(pat) return c = Chain(conf['IndexedRepos'], verbose) # init chain if opts.search: # --search search(c, pat) return if opts.info: # --info if len(args) != 1: p.error("Option requires one argument (name of package)") info_option(c, canonical(args[0])) return if opts.whats_new: # --whats-new if args: p.error("Option requires no arguments") whats_new(c) return if len(args) == 0: p.error("Requirement (name and optional version) missing") if len(args) > 2: p.error("A requirement is a name and an optional version") req = Req(' '.join(args)) if opts.remove: # --remove remove_req(req) return dists = get_dists(c, req, # dists recur=not opts.no_deps) # Warn the user about packages which depend on what will be updated depend_warn([dist_naming.filename_dist(d) for d in dists]) # Packages which are installed currently inst = set(egginst.get_installed()) # These are the packahes which are being excluded from being installed if opts.forceall: exclude = set() else: exclude = set(inst) if opts.force: exclude.discard(dist_naming.filename_dist(dists[-1])) # Fetch distributions if not isdir(conf['local']): os.makedirs(conf['local']) for dist in iter_dists_excl(dists, exclude): c.fetch_dist(dist, conf['local'], check_md5=opts.force or opts.forceall, dry_run=dry_run) # Remove packages (in reverse install order) for dist in dists[::-1]: fn = dist_naming.filename_dist(dist) if fn in inst: # if the distribution (which needs to be installed) is already # installed don't remove it continue cname = cname_fn(fn) for fn_inst in inst: if cname == cname_fn(fn_inst): egginst_remove(fn_inst) # Install packages installed_something = False for dist in iter_dists_excl(dists, exclude): installed_something = True egginst_install(conf, dist) if not installed_something: print "No update necessary, %s is up-to-date." % req print_installed_info(req.name)
#設定ファイル作成・書き込み import configparser config = configparser.ConfigParser() config['DEFAULT'] = { 'debug':False } config['web_server'] = { 'host' : '127.0.0.1', 'port' : 80 } config['db_server'] = { 'host' : '127.0.0.1', 'port' : 3306 } with open('config.ini','w') as config_file: config.write(config_file) #設定ファイル読み込み import configparser config = configparser.ConfigParser() config.read('config.ini') print(config['web_server']) print(config['web_server']['host']) print(config['web_server']['port']) print(config['DEFAULT']['debug']) ################################ #yaml