当前位置: 首页>>代码示例>>Python>>正文


Python SimpleXMLSerializer.set方法代码示例

本文整理汇总了Python中fife.extensions.serializers.simplexml.SimpleXMLSerializer.set方法的典型用法代码示例。如果您正苦于以下问题:Python SimpleXMLSerializer.set方法的具体用法?Python SimpleXMLSerializer.set怎么用?Python SimpleXMLSerializer.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在fife.extensions.serializers.simplexml.SimpleXMLSerializer的用法示例。


在下文中一共展示了SimpleXMLSerializer.set方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: serialize

# 需要导入模块: from fife.extensions.serializers.simplexml import SimpleXMLSerializer [as 别名]
# 或者: from fife.extensions.serializers.simplexml.SimpleXMLSerializer import set [as 别名]
	def serialize(self):
		filename = os.path.join("saves", self._mapname + "_save.xml")
		playerfilename = os.path.join("saves", "player_save.xml")
		map_settings = SimpleXMLSerializer(filename)
		player_settings = SimpleXMLSerializer(playerfilename)
		
		objectlist = []
		
		for obj in list(self._objectlist.values()):
			ovals = obj.serialize()
			map_settings.set("objects", obj.id, ovals)
			objectlist.append(obj.id)
			
		map_settings.set("objects", "objectlist", objectlist)
		
		pvals = self._player.serialize()
		player_settings.set("player", "player", pvals)
		
		map_settings.save()
		player_settings.save()
开发者ID:fifengine,项目名称:fifengine-demos,代码行数:22,代码来源:scene.py

示例2: _setup_settings

# 需要导入模块: from fife.extensions.serializers.simplexml import SimpleXMLSerializer [as 别名]
# 或者: from fife.extensions.serializers.simplexml.SimpleXMLSerializer import set [as 别名]
	def _setup_settings(self, check_file_version=True):
		_user_config_file = os.path.join( os.getcwd(), PATHS.USER_CONFIG_FILE )
		if check_file_version and os.path.exists(_user_config_file):
			# check if user settings file is the current one

			# NOTE: SimpleXMLSerializer can't handle relative paths, it fails silently
			# (although the doc states otherwise) - thus translate paths to absolute ones
			user_config_parser = SimpleXMLSerializer( _user_config_file )
			user_settings_version = user_config_parser.get("meta", "SettingsVersion", -1)
			_template_config_file = os.path.join( os.getcwd(), PATHS.CONFIG_TEMPLATE_FILE )
			template_config_parser = SimpleXMLSerializer( _template_config_file )
			template_settings_version = template_config_parser.get("meta", "SettingsVersion")

			if template_settings_version > user_settings_version: # we have to update the file
				print 'Discovered old settings file, auto-upgrading: %s -> %s' % \
				      (user_settings_version, template_settings_version)
				# create settings so we have a list of all settings
				self._setup_settings(check_file_version=False)

				# save settings here
				entries = []

				# need safe default value
				default_value = object()

				def update_value(modulename, entryname):
					# retrieve values from loaded settings file
					try:
						value = self._setting.get(modulename, entryname, default_value)
					except UnicodeEncodeError: # this can happen when unicode data is saved as str
						value = "default"
					if value is not default_value:
						entries.append( (modulename, entryname, value ) )

				# collect values from known settings and unreferenced settings
				for modulename, module in self._setting.entries.iteritems():
					for entryname in module.iterkeys():
						update_value(modulename, entryname)
				for modulename, entry_list in self.UNREFERENCED_SETTINGS.iteritems():
					for entryname in entry_list:
						update_value(modulename, entryname)

				# patch old values
				if user_settings_version <= 10:
					old_entries = entries
					entries = []
					for i in old_entries:
						if i[0] == UH_MODULE and i[1] == "Language":
							entries.append( (i[0], i[1], LANGUAGENAMES.get_by_value(i[2])) )
						else:
							entries.append(i)

				# write actual new file
				shutil.copy( PATHS.CONFIG_TEMPLATE_FILE, PATHS.USER_CONFIG_FILE )
				user_config_parser = SimpleXMLSerializer( _user_config_file )
				for modulename, entryname, value in entries:
					user_config_parser.set(modulename, entryname, value)
				user_config_parser.save()

		self._setting = SettingsDialog(app_name=UH_MODULE,
				                         settings_file=PATHS.USER_CONFIG_FILE,
				                         settings_gui_xml="settings.xml",
				                         changes_gui_xml="requirerestart.xml",
				                         default_settings_file=PATHS.CONFIG_TEMPLATE_FILE)

		self._setting_handler.add_settings()
开发者ID:DanielStephens,项目名称:unknown-horizons,代码行数:68,代码来源:engine.py

示例3: __init__

# 需要导入模块: from fife.extensions.serializers.simplexml import SimpleXMLSerializer [as 别名]
# 或者: from fife.extensions.serializers.simplexml.SimpleXMLSerializer import set [as 别名]
class Settings:

	# Settings key storing the SettingsVersion used to upgrade settings
	SETTINGS_VERSION = "SettingsVersion"

	def __init__(self, settings_file, settings_template_file):
		self._module_settings = {}
		self._module_settings_template = {}
		self._settings_file = settings_file
		self._settings_template_file = settings_template_file
		self._settings_serializer = SimpleXMLSerializer()
		self._settings_serializer.load(settings_file)
		self._settings_template_serializer = SimpleXMLSerializer()
		self._settings_template_serializer.load(settings_template_file)
		if not hasattr(self._settings_template_serializer, 'getModuleName'):
			# Renamed after 0.3.5: https://github.com/fifengine/fifengine/issues/819.
			new_api = self._settings_template_serializer.getModuleNameList
			self._settings_template_serializer.getModuleName = new_api
		self.upgrade_settings()

	def get(self, module, name, default=None):
		if default is None:
			default = self._settings_template_serializer.get(module, name)

		v = self._settings_serializer.get(module, name, default)
		getter = getattr(self, 'get_' + module + '_' + name, None)
		if getter:
			return getter(v)
		else:
			return v

	def set(self, module, name, value):
		setter = getattr(self, 'set_' + module + '_' + name, None)
		if setter:
			value = setter(value)

		# This is necessary, as empty fields return None, but saving
		# None will result in the String 'None' being stored
		if value is None:
			value = ''

		if module in self._module_settings:
			self._module_settings[module][name] = value

		self._settings_serializer.set(module, name, value, {})

	def get_module_settings(self, module):
		self._module_settings[module] = self._settings_serializer.getAllSettings(module)
		self._module_settings_template[module] = self._settings_template_serializer.getAllSettings(module)
		for name, value in self._module_settings_template[module].items():
			if name not in self._module_settings[module]:
				self._module_settings[module][name] = value
		return self._module_settings[module]

	def get_module_template_settings(self, module):
		return self._settings_template_serializer.getAllSettings(module)

	def save(self):
		self._settings_serializer.save(self._settings_file)

	def apply(self):
		data = self.get(SETTINGS.UH_MODULE, "Language")
		language = LANGUAGENAMES.get_by_value(data)
		change_language(language)

	def set_defaults(self):
		for module in self._settings_template_serializer.getModuleName():
			for setting_name in self._settings_template_serializer.getAllSettings(module):
				value = self._settings_template_serializer.get(module, setting_name)
				self.set(module, setting_name, value)
		self.save()

	def upgrade_settings(self):
		"""Upgrades the settings to a newer version necessary."""
		# if the settings file doesn't exist, force an update with
		# settings version 1 as default value
		current_version = self.get(SETTINGS.META_MODULE, self.SETTINGS_VERSION, 1)
		template_version = self._settings_template_serializer.get(SETTINGS.META_MODULE, self.SETTINGS_VERSION)
		if current_version != template_version:
			print('Discovered old settings file, auto-upgrading: {} -> {}'.format(
		          current_version, template_version))
			for module in self._settings_template_serializer.getModuleName():
				for setting_name in self._settings_template_serializer.getAllSettings(module):
					default_value = self._settings_template_serializer.get(module, setting_name)
					if self.get(module, setting_name, default=default_value) is default_value:
						self.set(module, setting_name, default_value)
			self.set(SETTINGS.META_MODULE, self.SETTINGS_VERSION, template_version)
			self.save()

	# settings

	def get_unknownhorizons_Language(self, value):
		if value is None: # the entry is None for empty strings
			value = ""
		return LANGUAGENAMES[value]

	def set_unknownhorizons_Language(self, value):
		return LANGUAGENAMES.get_by_value(value)
开发者ID:MarkusHackspacher,项目名称:unknown-horizons,代码行数:100,代码来源:settings.py

示例4: Setting

# 需要导入模块: from fife.extensions.serializers.simplexml import SimpleXMLSerializer [as 别名]
# 或者: from fife.extensions.serializers.simplexml.SimpleXMLSerializer import set [as 别名]
class Setting(object):
	"""
	This class manages loading and saving of game settings.

	Usage::
		from fife.extensions.fife_settings import Setting
		settings = Setting(app_name="myapp")
		screen_width = settings.get("FIFE", "ScreenWidth", 1024)
		screen_height = settings.get("FIFE", "ScreenHeight", 768)
	"""

	def __init__(self, app_name="", settings_file="", default_settings_file= "settings-dist.xml", copy_dist=True, serializer=None):
		"""
		Initializes the Setting object.

		@param app_name: The applications name.  If this parameter is provided
		alone it will try to read the settings file from the users home directory.
		In windows this will be	something like:	C:\Documents and Settings\user\Application Data\fife
		@type app_name: C{string}
		@param settings_file: The name of the settings file.  If this parameter is
		provided it will look for the setting file as you specify it, first looking
		in the working directory.  It will NOT look in the users home directory.
		@type settings_file: C{string}
		@param default_settings_file: The name of the default settings file.  If the settings_file
		does not exist this file will be copied into the place of the settings_file.  This file
		must exist in the root directory of your project!
		@type default_settings_file: C{string}
		@param settings_gui_xml: If you specify this parameter you can customize the look
		of the settings dialog box.
		@param copy_dist: Copies the default settings file to the settings_file location.  If
		this is False it will create a new empty setting file.
		@param serializer: Overrides the default XML serializer
		@type serializer: C{SimpleSerializer}

		"""
		self._app_name = app_name
		self._settings_file = settings_file
		self._default_settings_file = default_settings_file

		# Holds SettingEntries
		self._entries = {}

		if self._settings_file == "":
			self._settings_file = "settings.xml"
			self._appdata = getUserDataDirectory("fife", self._app_name)
		else:
			self._appdata = os.path.dirname(self._settings_file)
			self._settings_file = os.path.basename(self._settings_file)

		if not os.path.exists(os.path.join(self._appdata, self._settings_file)):
			if os.path.exists(self._default_settings_file) and copy_dist:
				shutil.copyfile(self._default_settings_file, os.path.join(self._appdata, self._settings_file))

		# valid values possible for the engineSettings
		self._validSetting = {}
		self._validSetting['FIFE'] = {
			'FullScreen':[True,False], 'PychanDebug':[True,False]
			, 'ProfilingOn':[True,False], 'SDLRemoveFakeAlpha':[True,False], 'GLCompressImages':[False,True], 'GLUseFramebuffer':[False,True], 'GLUseNPOT':[False,True],
			'GLUseMipmapping':[False,True], 'GLTextureFiltering':['None', 'Bilinear', 'Trilinear', 'Anisotropic'], 'GLUseMonochrome':[False,True],
			'GLUseDepthBuffer':[False,True], 'GLAlphaTestValue':[0.0,1.0],
			'RenderBackend':['OpenGL', 'SDL'],
			'ScreenResolution':['640x480', '800x600', '1024x600', '1024x768', '1280x768',
								'1280x800', '1280x960', '1280x1024', '1366x768', '1440x900',
								'1600x900', '1600x1200', '1680x1050', '1920x1080', '1920x1200'],
			'BitsPerPixel':[0,16,24,32],
			'InitialVolume':[0.0,10.0], 'WindowTitle':"", 'WindowIcon':"", 'Font':"",
			'FontGlyphs':"", 'DefaultFontSize':"", 'Lighting':[0,1],
			'ColorKeyEnabled':[True,False], 'ColorKey':['a','b','c'], 'VideoDriver':"",
			'PlaySounds':[True,False], 'LogToFile':[True,False],
			'LogToPrompt':[True,False],'UsePsyco':[True,False], 'LogLevelFilter':[0,1,2,3],
			'LogModules':['all', 'controller','script','video','audio','loaders','vfs','pool','view','model','metamodel','event_channel','xml'],
			'FrameLimitEnabled':[True,False], 'FrameLimit':[0], 'MouseSensitivity':[0.0], 'MouseAcceleration':[True,False]
			}

		glyphDft = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.,!?-+/():;%&amp;`'*#=[]\\\""

		# we at this point assume default values are final values for engineSettings
		self._defaultSetting = {}
		self._defaultSetting['FIFE'] = {
			'FullScreen':False, 'PychanDebug':False
			, 'ProfilingOn':False, 'SDLRemoveFakeAlpha':False, 'GLCompressImages':False, 'GLUseFramebuffer':True, 'GLUseNPOT':True,
			'GLUseMipmapping':False, 'GLTextureFiltering':'None', 'GLUseMonochrome':False, 'GLUseDepthBuffer':False, 'GLAlphaTestValue':0.3,
			'RenderBackend':'OpenGL', 'ScreenResolution':"1024x768", 'BitsPerPixel':0,
			'InitialVolume':5.0, 'WindowTitle':"", 'WindowIcon':"", 'Font':"",
			'FontGlyphs':glyphDft, 'DefaultFontSize':12, 'Lighting':0,
			'ColorKeyEnabled':False, 'ColorKey':[255,0,255], 'VideoDriver':"",
			'PlaySounds':True, 'LogToFile':False,
			'LogToPrompt':False,'UsePsyco':False,'LogLevelFilter':[0],
			'LogModules':['controller','script'],
			'FrameLimitEnabled':False, 'FrameLimit':60,
			'MouseSensitivity':0.0,
			'MouseAcceleration':False
			}

		# has the settings file been read
		self._readSettingsCompleted = {}

		# the global dictionary from which we will read after self._readSettingsCompleted is True
		self._settingsFromFile = {}

#.........这里部分代码省略.........
开发者ID:cheif,项目名称:fifengine,代码行数:103,代码来源:fife_settings.py

示例5: Setting

# 需要导入模块: from fife.extensions.serializers.simplexml import SimpleXMLSerializer [as 别名]
# 或者: from fife.extensions.serializers.simplexml.SimpleXMLSerializer import set [as 别名]
class Setting(object):
	"""
	This class manages loading and saving of game settings.

	Usage::
		from fife.extensions.fife_settings import Setting
		settings = Setting(app_name="myapp")
		screen_width = settings.get("FIFE", "ScreenWidth", 1024)
		screen_height = settings.get("FIFE", "ScreenHeight", 768)
	"""

	def __init__(self, app_name="", settings_file="", default_settings_file= "settings-dist.xml", settings_gui_xml="", changes_gui_xml="", copy_dist=True, serializer=None):
		"""
		Initializes the Setting object.

		@param app_name: The applications name.  If this parameter is provided
		alone it will try to read the settings file from the users home directory.
		In windows this will be	something like:	C:\Documents and Settings\user\Application Data\fife
		@type app_name: C{string}
		@param settings_file: The name of the settings file.  If this parameter is
		provided it will look for the setting file as you specify it, first looking
		in the working directory.  It will NOT look in the users home directory.
		@type settings_file: C{string}
		@param default_settings_file: The name of the default settings file.  If the settings_file
		does not exist this file will be copied into the place of the settings_file.  This file
		must exist in the root directory of your project!
		@type default_settings_file: C{string}
		@param settings_gui_xml: If you specify this parameter you can customize the look
		of the settings dialog box.
		@param copy_dist: Copies the default settings file to the settings_file location.  If
		this is False it will create a new empty setting file.
		@param serializer: Overrides the default XML serializer
		@type serializer: C{SimpleSerializer}

		"""
		self._app_name = app_name
		self._settings_file = settings_file
		self._default_settings_file = default_settings_file
		self._settings_gui_xml = settings_gui_xml
		self._changes_gui_xml = changes_gui_xml
		self.OptionsDlg = None

		# Holds SettingEntries
		self._entries = {}
		
		if self._settings_file == "":
			self._settings_file = "settings.xml"
			self._appdata = getUserDataDirectory("fife", self._app_name)
		else:
			self._appdata = os.path.dirname(self._settings_file)
			self._settings_file = os.path.basename(self._settings_file)


		if self._settings_gui_xml == "":
			self._settings_gui_xml = SETTINGS_GUI_XML

		if self._changes_gui_xml == "":
			self._changes_gui_xml = CHANGES_REQUIRE_RESTART


		if not os.path.exists(os.path.join(self._appdata, self._settings_file)):
			if os.path.exists(self._default_settings_file) and copy_dist:
				shutil.copyfile(self._default_settings_file, os.path.join(self._appdata, self._settings_file))

		#default settings
		self._resolutions = ['640x480', '800x600', '1024x768', '1280x800', '1440x900']
		self._renderbackends = ['OpenGL', 'SDL']
		self._lightingmodels = [0, 1, 2]

		#Used to stylize the options gui
		self._gui_style = "default"

		#Initialize the serializer
		if serializer:
			self._serializer = serializer
		else:
			self._serializer = SimpleXMLSerializer()
	
		self.initSerializer()
	
		self._initDefaultSettingEntries()

	def initSerializer(self):
		self._serializer.load(os.path.join(self._appdata, self._settings_file))
		
	def _initDefaultSettingEntries(self):
		"""Initializes the default fife setting entries. Not to be called from
		outside this class."""
		self.createAndAddEntry(FIFE_MODULE, "PlaySounds", "enable_sound",
		              requiresrestart=True)
		self.createAndAddEntry(FIFE_MODULE, "FullScreen", "enable_fullscreen",
		              requiresrestart=True)
		self.createAndAddEntry(FIFE_MODULE, "ScreenResolution", "screen_resolution", initialdata = self._resolutions,
		              requiresrestart=True)
		self.createAndAddEntry(FIFE_MODULE, "RenderBackend", "render_backend", initialdata = self._renderbackends,
		              requiresrestart=True)
		self.createAndAddEntry(FIFE_MODULE, "Lighting", "lighting_model", initialdata = self._lightingmodels,
		              requiresrestart=True)

	def createAndAddEntry(self, module, name, widgetname, applyfunction=None, initialdata=None, requiresrestart=False):
#.........这里部分代码省略.........
开发者ID:mgeorgehansen,项目名称:FIFE_Technomage,代码行数:103,代码来源:fife_settings.py

示例6: _setup_settings

# 需要导入模块: from fife.extensions.serializers.simplexml import SimpleXMLSerializer [as 别名]
# 或者: from fife.extensions.serializers.simplexml.SimpleXMLSerializer import set [as 别名]
	def _setup_settings(self, check_file_version=True):
		_user_config_file = os.path.join( os.getcwd(), PATHS.USER_CONFIG_FILE )
		if not os.path.exists(_user_config_file):
			check_file_version = False
		if check_file_version:
			# check if user settings file is the current one

			# NOTE: SimpleXMLSerializer can't handle relative paths, it fails silently
			# (although the doc states otherwise) - thus translate paths to absolute ones
			user_config_parser = SimpleXMLSerializer( _user_config_file )
			user_settings_version = user_config_parser.get("meta", "SettingsVersion", -1)
			_template_config_file = os.path.join( os.getcwd(), PATHS.CONFIG_TEMPLATE_FILE )
			template_config_parser = SimpleXMLSerializer( _template_config_file )
			template_settings_version = template_config_parser.get("meta", "SettingsVersion")

			if template_settings_version > user_settings_version: # we have to update the file
				# create settings so we have a list of all settings
				self._setup_settings(check_file_version=False)

				# save settings here
				entries = []
				def update_value(modulename, entryname):
					# retrieve values from loaded settings file
					try:
						value = self._setting.get(modulename, entryname)
					except UnicodeEncodeError: # this can happen when unicode data is saved as str
						value = "default"
					entries.append( (modulename, entryname, value ) )

				# update known settings and unreferenced settings
				for modulename, module in self._setting.entries.iteritems():
					for entryname in module.iterkeys():
						update_value(modulename, entryname)
				for modulename, entry_list in self.UNREFERENCED_SETTINGS.iteritems():
					for entryname in entry_list:
						update_value(modulename, entryname)

				# write actual new file
				shutil.copy( PATHS.CONFIG_TEMPLATE_FILE, PATHS.USER_CONFIG_FILE )
				user_config_parser = SimpleXMLSerializer( _user_config_file )
				for modulename, entryname, value in entries:
					user_config_parser.set(modulename, entryname, value)
				user_config_parser.save()

		self._setting = LocalizedSetting(app_name=UH_MODULE,
		                                 settings_file=PATHS.USER_CONFIG_FILE,
		                                 settings_gui_xml="settings.xml",
		                                 changes_gui_xml="requirerestart.xml",
		                                 default_settings_file=PATHS.CONFIG_TEMPLATE_FILE)

		# TODO: find a way to apply changing to a running game in a clean fashion
		#       possibility: use singaling via changelistener
		def update_minimap(*args):
			try: horizons.main._modules.session.ingame_gui.minimap.draw()
			except AttributeError: pass # session or gui not yet initialised

		def update_autosave_interval(*args):
			try: horizons.main._modules.session.reset_autosave()
			except AttributeError: pass # session or gui not yet initialised


		#self.createAndAddEntry(self, module, name, widgetname, applyfunction=None, initialdata=None, requiresrestart=False)
		self._setting.createAndAddEntry(UH_MODULE, "AutosaveInterval", "autosaveinterval",
		                                applyfunction=update_autosave_interval)
		self._setting.createAndAddEntry(UH_MODULE, "AutosaveMaxCount", "autosavemaxcount")
		self._setting.createAndAddEntry(UH_MODULE, "QuicksaveMaxCount", "quicksavemaxcount")
		self._setting.createAndAddEntry(UH_MODULE, "EdgeScrolling", "edgescrolling")
		self._setting.createAndAddEntry(UH_MODULE, "UninterruptedBuilding", "uninterrupted_building")

		self._setting.createAndAddEntry(UH_MODULE, "MinimapRotation", "minimaprotation", \
		                                applyfunction=update_minimap)

		self._setting.createAndAddEntry(FIFE_MODULE, "BitsPerPixel", "screen_bpp",
		                                initialdata=[0, 16, 32], requiresrestart=True)

		languages_map = dict(find_available_languages())
		languages_map[_('System default')] = ''
		# English is not shipped as .mo file.
		languages_map['en'] = ''

		self._setting.createAndAddEntry(UH_MODULE, "Language", "language",
		                                applyfunction=self.update_languages,
		                                initialdata= [LANGUAGENAMES[x] for x in sorted(languages_map.keys())])
		self._setting.createAndAddEntry(UH_MODULE, "VolumeMusic", "volume_music",
		                                applyfunction=self.set_volume_music)
		self._setting.createAndAddEntry(UH_MODULE, "VolumeEffects", "volume_effects",
		                                applyfunction=self.set_volume_effects)

		self._setting.createAndAddEntry(UH_MODULE, "NetworkPort", "network_port",
		                                applyfunction=self.set_network_port)


		self._setting.entries[FIFE_MODULE]['PlaySounds'].applyfunction = lambda x: self.setup_sound()
		self._setting.entries[FIFE_MODULE]['PlaySounds'].requiresrestart = False

		self._setting.entries[FIFE_MODULE]['RenderBackend'].applyfunction = lambda x: self._show_renderbackend_warning()
开发者ID:slbucur,项目名称:unknown-horizons,代码行数:98,代码来源:engine.py

示例7: raw_input

# 需要导入模块: from fife.extensions.serializers.simplexml import SimpleXMLSerializer [as 别名]
# 或者: from fife.extensions.serializers.simplexml.SimpleXMLSerializer import set [as 别名]
if os.path.isdir(fife_path) and fife_path not in sys.path:
	sys.path.insert(0,fife_path)

# Load the XML Serialiser:
from fife.extensions.serializers.simplexml import SimpleXMLSerializer

print """ ____  _  ____  _____  _  ____  _  ____ _____ 
| _) \| |/ (__`|_   _|| || ===|| || ===|| () )
|____/|_|\____)  |_|  |_||__|  |_||____||_|\_\

Python Dict to FIFE XML Serial Format Converter
"""

filename = raw_input("XML Filename: ")
xml = SimpleXMLSerializer(filename)

dict = {}
loop = True

while loop:
    key = raw_input("Key: ")
    dict[key] = raw_input("Value: ")
    print "Add more? Y/n"
    if raw_input() == "n":
        loop = False
        
dictstore = xml._serializeDict(dict)
xml.set(raw_input("Module: "), raw_input("Name: "), dictstore)
xml.save(filename)
print filename + " has been updated with the new dict entry. Press enter to end this python shell"
raw_input()
开发者ID:Drakekin,项目名称:Zero-Sum-Cascade-Old,代码行数:33,代码来源:dictify.py

示例8: Settings

# 需要导入模块: from fife.extensions.serializers.simplexml import SimpleXMLSerializer [as 别名]
# 或者: from fife.extensions.serializers.simplexml.SimpleXMLSerializer import set [as 别名]
class Settings(object):

	# Settings key storing the SettingsVersion used to upgrade settings
	SETTINGS_VERSION = "SettingsVersion"

	def __init__(self, settings_file, settings_template_file):
		self._module_settings = {}
		self._module_settings_template = {}
		self._settings_file = settings_file
		self._settings_template_file = settings_template_file
		self._settings_serializer = SimpleXMLSerializer()
		self._settings_serializer.load(settings_file)
		self._settings_template_serializer = SimpleXMLSerializer()
		self._settings_template_serializer.load(settings_template_file)
		self.upgrade_settings()

	def get(self, module, name, default=None):
		if default is None:
			default = self._settings_template_serializer.get(module, name)

		v = self._settings_serializer.get(module, name, default)
		getter = getattr(self, 'get_' + module + '_' + name, None)
		if getter:
			return getter(v)
		else:
			return v

	def set(self, module, name, value):
		setter = getattr(self, 'set_' + module + '_' + name, None)
		if setter:
			value = setter(value)

		# This is necessary, as empty fields return None, but saving
		# None will result in the String 'None' being stored
		if value is None:
			value = ''

		if module in self._module_settings:
			self._module_settings[module][name] = value

		self._settings_serializer.set(module, name, value, {})

	def get_module_settings(self, module):
		self._module_settings[module] = self._settings_serializer.getAllSettings(module)
		self._module_settings_template[module] = self._settings_template_serializer.getAllSettings(module)
		for name, value in self._module_settings_template[module].iteritems():
			if name not in self._module_settings[module]:
				self._module_settings[module][name] = value
		return self._module_settings[module]

	def get_module_template_settings(self, module):
		return self._settings_template_serializer.getAllSettings(module)

	def save(self):
		self._settings_serializer.save(self._settings_file)

	def apply(self):
		data = self.get(SETTINGS.UH_MODULE, "Language")
		language = LANGUAGENAMES.get_by_value(data)
		change_language(language)

	def set_defaults(self):
		for module in self._settings_template_serializer.getModuleName():
			for setting_name in self._settings_template_serializer.getAllSettings(module):
				value = self._settings_template_serializer.get(module, setting_name)
				self.set(module, setting_name, value)
		self.save()

	def upgrade_settings(self):
		"""Upgrades the settings to a newer version necessary."""
		current_version = self.get(SETTINGS.META_MODULE, self.SETTINGS_VERSION)
		template_version = self._settings_template_serializer.get(SETTINGS.META_MODULE, self.SETTINGS_VERSION)
		if current_version != template_version:
			print 'Discovered old settings file, auto-upgrading: %s -> %s' % \
		          (current_version, template_version)
			for module in self._settings_template_serializer.getModuleName():
				for setting_name in self._settings_template_serializer.getAllSettings(module):
					default_value = self._settings_template_serializer.get(module, setting_name)
					if self.get(module, setting_name, default=default_value) is default_value:
						self.set(module, setting_name, default_value)
			self.set(SETTINGS.META_MODULE, self.SETTINGS_VERSION, template_version)
			self.save()

	# settings

	def get_unknownhorizons_Language(self, value):
		if value is None: # the entry is None for empty strings
			value = ""
		return LANGUAGENAMES[value]

	def set_unknownhorizons_Language(self, value):
		return LANGUAGENAMES.get_by_value(value)
开发者ID:JonathanMeans,项目名称:unknown-horizons,代码行数:94,代码来源:settings.py


注:本文中的fife.extensions.serializers.simplexml.SimpleXMLSerializer.set方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。