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


Python ConfigParser.write方法代码示例

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


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

示例1: ProjectSettings

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class ProjectSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of project.
    '''

    project = ObjectProperty(None)
    '''Reference to :class:`desginer.project_manager.Project`
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''

    def load_proj_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser()
        file_path = os.path.join(self.project.path, PROJ_CONFIG)
        if not os.path.exists(file_path):
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))

            CONFIG_TEMPLATE = '''[proj_name]
name = Project

[arguments]
arg =

[env variables]
env =
'''
            f = open(file_path, 'w')
            f.write(CONFIG_TEMPLATE)
            f.close()

        self.config_parser.read(file_path)
        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]
        settings_dir = os.path.join(_dir, 'designer', 'settings')
        self.add_json_panel('Shell Environment',
                            self.config_parser,
                            os.path.join(settings_dir,
                                         'proj_settings_shell_env.json'))
        self.add_json_panel('Project Properties',
                            self.config_parser,
                            os.path.join(settings_dir,
                                         'proj_settings_proj_prop.json'))

    @ignore_proj_watcher
    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(ProjectSettings, self).on_config_change(*args)
开发者ID:Python-PyBD,项目名称:kivy-designer,代码行数:57,代码来源:project_settings.py

示例2: load_config

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
    def load_config(self):
        '''(internal) This function is used for returning a ConfigParser with
        the application configuration. It's doing 3 things:

            #. Creating an instance of a ConfigParser
            #. Loading the default configuration by calling
               :meth:`build_config`, then
            #. If it exists, it loads the application configuration file,
               otherwise it creates one.

        :return:
            :class:`~kivy.config.ConfigParser` instance
        '''
        try:
            config = ConfigParser.get_configparser('app')
        except KeyError:
            config = None
        if config is None:
            config = ConfigParser(name='app')
        self.config = config
        self.build_config(config)
        # if no sections are created, that's mean the user don't have
        # configuration.
        if len(config.sections()) == 0:
            return
        # ok, the user have some sections, read the default file if exist
        # or write it !
        filename = self.get_application_config()
        if filename is None:
            return config
        Logger.debug('App: Loading configuration <{0}>'.format(filename))
        if exists(filename):
            try:
                config.read(filename)
            except:
                Logger.error('App: Corrupted config file, ignored.')
                config.name = ''
                try:
                    config = ConfigParser.get_configparser('app')
                except KeyError:
                    config = None
                if config is None:
                    config = ConfigParser(name='app')
                self.config = config
                self.build_config(config)
                pass
        else:
            Logger.debug('App: First configuration, create <{0}>'.format(
                filename))
            config.filename = filename
            config.write()
        return config
开发者ID:AndiEcker,项目名称:kivy,代码行数:54,代码来源:app.py

示例3: ProjectSettings

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class ProjectSettings(Settings):
    """Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of project.
    """

    project = ObjectProperty(None)
    """Reference to :class:`desginer.project_manager.Project`
    """

    config_parser = ObjectProperty(None)
    """Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    """

    def load_proj_settings(self):
        """This function loads project settings
        """
        self.config_parser = ConfigParser()
        file_path = os.path.join(self.project.path, PROJ_CONFIG)
        if not os.path.exists(file_path):
            if not os.path.exists(os.path.dirname(file_path)):
                os.makedirs(os.path.dirname(file_path))

            CONFIG_TEMPLATE = """[proj_name]
name = Project

[arguments]
arg =

[env variables]
env =
"""
            f = open(file_path, "w")
            f.write(CONFIG_TEMPLATE)
            f.close()

        self.config_parser.read(file_path)

        settings_dir = os.path.join(get_kd_data_dir(), "settings")
        self.add_json_panel(
            "Shell Environment", self.config_parser, os.path.join(settings_dir, "proj_settings_shell_env.json")
        )
        self.add_json_panel(
            "Project Properties", self.config_parser, os.path.join(settings_dir, "proj_settings_proj_prop.json")
        )

    @ignore_proj_watcher
    def on_config_change(self, *args):
        """This function is default handler of on_config_change event.
        """
        self.config_parser.write()
        super(ProjectSettings, self).on_config_change(*args)
开发者ID:kivy,项目名称:kivy-designer,代码行数:54,代码来源:project_settings.py

示例4: DesignerSettings

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class DesignerSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''

    def load_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser()
        DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(),
                                       DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME)
        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG,
                            DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)
        self.add_json_panel('Kivy Designer Settings', self.config_parser,
                            os.path.join(_dir, 'designer',
                                         'settings', 'designer_settings.json'))

        path = self.config_parser.getdefault(
            'global', 'python_shell_path', '')

        if path == "":
            self.config_parser.set('global', 'python_shell_path',
                                   sys.executable)
            self.config_parser.write()

    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
开发者ID:dessant,项目名称:kivy-designer,代码行数:46,代码来源:designer_settings.py

示例5: on_new

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
    def on_new(self, *args):
        '''Handler for "New Profile" button
        '''
        new_name = 'new_profile'
        i = 1
        while os.path.exists(os.path.join(
                self.PROFILES_PATH, new_name + str(i) + '.ini')):
            i += 1
        new_name += str(i)
        new_prof_path = os.path.join(
            self.PROFILES_PATH, new_name + '.ini')

        shutil.copy2(os.path.join(self.DEFAULT_PROFILES, 'desktop.ini'),
                     new_prof_path)
        config_parser = ConfigParser()
        config_parser.read(new_prof_path)
        config_parser.set('profile', 'name', new_name.upper())
        config_parser.write()

        self.update_panel()
        self.settings_changed = True
开发者ID:kivy,项目名称:kivy-designer,代码行数:23,代码来源:profile_settings.py

示例6: DesignerSettings

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class DesignerSettings(Settings):
    """Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    """

    config_parser = ObjectProperty(None)
    """Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    """

    def load_settings(self):
        """This function loads project settings
        """
        self.config_parser = ConfigParser()
        DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(), DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME), DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.add_json_panel(
            "Kivy Designer Settings",
            self.config_parser,
            os.path.join(_dir, "designer", "settings", "designer_settings.json"),
        )

        path = self.config_parser.getdefault("global", "python_shell_path", "")

        if path == "":
            self.config_parser.set("global", "python_shell_path", sys.executable)
            self.config_parser.write()

    def on_config_change(self, *args):
        """This function is default handler of on_config_change event.
        """
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
开发者ID:kingctan,项目名称:kivy-designer,代码行数:42,代码来源:designer_settings.py

示例7: cBaseScript

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class cBaseScript(object):
    ''' basic script class to inherit all scrpts from '''
    def __init__(self):
        self.bIsInit                = False
        self.uMyPath                = u''
        self.uScriptName            = u''
        self.uScriptFile            = u''
        self.iMyVersion             = ToIntVersion('1.0.0')
        self.fOrcaVersion           = ToIntVersion('1.0.0')
        self.uType                  = u'Generic'
        self.uSubType               = u'Generic'
        self.aScriptIniSettings     = QueryDict()
        self.oConfigParser          = KivyConfigParser()
        self.uDefaultConfigName     = ""
        self.uConfigFileName        = ""
        self.uSection               = ""

    def RunScript(self, args):
        ''' Dummy '''
        pass

    def Init(self,oParORCA,uScriptName,uScriptFile):
        ''' Initializes the script '''
        self.bIsInit            = True
        self.uScriptName        = uScriptName
        self.uScriptFile        = uScriptFile
        self.uDefaultConfigName = uScriptName

        self.uMyPath            = AdjustPathToOs(oORCA.uScriptsPath+'/'+self.uScriptName)
        if not os.path.exists(self.uMyPath):
            CreateDir(self.uMyPath)
        oORCA.oTheScreen.oLanguage.LoadXmlFile("SCRIPT", uScriptName)

        self.uConfigFileName    = AdjustPathToOs(self.uMyPath+u'/config.ini')
        oRepManagerEntry=cRepManagerEntry()
        oRepManagerEntry.uFileName=uScriptFile
        if oRepManagerEntry.ParseFromSourceFile():
            self.iMyVersion     = oRepManagerEntry.oRepEntry.iVersion
            self.fOrcaVersion   = oRepManagerEntry.oRepEntry.iMinOrcaVersion
            #OrcaVersion defines for what Orca Version the Interface has been developed

        self.ShowDebug(u'Init')
        if not FileExists(self.uConfigFileName):
            self.CreateAndInitializeIniFile()

        oRepManagerEntry=cRepManagerEntry()
        oRepManagerEntry.uFileName=uScriptFile
        if oRepManagerEntry.ParseFromSourceFile():
            self.iMyVersion     = oRepManagerEntry.oRepEntry.iVersion
            self.fOrcaVersion   = oRepManagerEntry.oRepEntry.iMinOrcaVersion
            #OrcaVersion defines for what Orca Version the Script has been developed
        self.ReadConfigFromIniFile(self.uDefaultConfigName)

    def InitializeSection(self,uSection):
        ''' Initializes a section in the config.ini file for the script '''
        self.ReadConfigFromIniFile(uSection)
    def CreateAndInitializeIniFile(self):
        ''' Creates the ini file '''
        self.oConfigParser.add_section(self.uDefaultConfigName)
        self.InitializeSection(self.uDefaultConfigName)
        self.oConfigParser.write()
    def LoadConfig(self):
        ''' loads a config from the ini file '''
        self.oConfigParser.filename=self.uConfigFileName
        if len(self.oConfigParser._sections)==0:
            if FileExists(self.uConfigFileName):
                self.ShowDebug(u'Reading Config File')
                self.oConfigParser.read(self.uConfigFileName)
    def GetConfigJSONStringforSection(self,uSection):
        ''' dummy '''
        return u'{}'

    def ReadConfigFromIniFile(self,uConfigName):
        ''' reads a config from the ini file '''
        self.uSection = uConfigName

        try:
            SetVar('ScriptConfigSection',uConfigName)
            self.LoadConfig()
            oIniDef = json.loads(self.GetConfigJSONStringforSection(uConfigName))

            for oLine in oIniDef:
                uType       = oLine.get("type")
                uKey        = oLine.get("key")
                uDefault    = oLine.get("default")

                if uType == "scrolloptions" or uType == "string":
                    uPre = "u" + uKey
                    self.aScriptIniSettings[uPre]=Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault)
                elif uType == "numeric" or uType == "numericslider":
                    uPre= "i" + uKey
                    self.aScriptIniSettings[uPre]=ToInt(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "numericfloat" :
                    uPre= "f" + uKey
                    self.aScriptIniSettings[uPre]=ToFloat(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "bool":
                    uPre = "b" + uKey
                    self.aScriptIniSettings[uPre]=ToBool(Config_getdefault(self.oConfigParser,self.uSection, uKey,uDefault))
                elif uType == "title":
                    pass
#.........这里部分代码省略.........
开发者ID:thica,项目名称:ORCA-Remote,代码行数:103,代码来源:ScriptClass.py

示例8: DesignerSettings

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class DesignerSettings(Settings):
    '''Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    '''

    config_parser = ObjectProperty(None)
    '''Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    '''

    def __init__(self, **kwargs):
        super(DesignerSettings, self).__init__(*kwargs)
        self.register_type('list', SettingList)
        self.register_type('shortcut', SettingShortcut)

    def load_settings(self):
        '''This function loads project settings
        '''
        self.config_parser = ConfigParser(name='DesignerSettings')
        DESIGNER_CONFIG = os.path.join(get_config_dir(),
                                       DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME)
        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG,
                            DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)

        # creates a panel before insert it to update code input theme list
        panel = self.create_json_panel('Kivy Designer Settings',
                                        self.config_parser,
                            os.path.join(_dir, 'designer',
                                         'settings', 'designer_settings.json'))
        uid = panel.uid
        if self.interface is not None:
            self.interface.add_panel(panel, 'Kivy Designer Settings', uid)

        # loads available themes
        for child in panel.children:
            if child.id == 'code_input_theme_options':
                child.items = styles.get_all_styles()

        # tries to find python and buildozer path if it's not defined
        path = self.config_parser.getdefault(
            'global', 'python_shell_path', '')

        if path.strip() == '':
            self.config_parser.set('global', 'python_shell_path',
                                   sys.executable)
            self.config_parser.write()

        buildozer_path = self.config_parser.getdefault('buildozer',
                                                       'buildozer_path', '')

        if buildozer_path.strip() == '':
            buildozer_path = find_executable('buildozer')
            if buildozer_path:
                self.config_parser.set('buildozer',
                                       'buildozer_path',
                                        buildozer_path)
                self.config_parser.write()

        self.add_json_panel('Buildozer', self.config_parser,
                            os.path.join(_dir, 'designer', 'settings',
                                         'buildozer_settings.json'))
        self.add_json_panel('Hanga', self.config_parser,
                            os.path.join(_dir, 'designer', 'settings',
                                         'hanga_settings.json'))
        self.add_json_panel('Keyboard Shortcuts', self.config_parser,
                            os.path.join(_dir, 'designer', 'settings',
                                         'shortcuts.json'))

    def on_config_change(self, *args):
        '''This function is default handler of on_config_change event.
        '''
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
开发者ID:Python-PyBD,项目名称:kivy-designer,代码行数:84,代码来源:designer_settings.py

示例9: DesignerSettings

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class DesignerSettings(Settings):
    """Subclass of :class:`kivy.uix.settings.Settings` responsible for
       showing settings of Kivy Designer.
    """

    config_parser = ObjectProperty(None)
    """Config Parser for this class. Instance
       of :class:`kivy.config.ConfigParser`
    """

    def __init__(self, **kwargs):
        super(DesignerSettings, self).__init__(*kwargs)
        self.register_type("list", SettingList)
        self.register_type("shortcut", SettingShortcut)

    def load_settings(self):
        """This function loads project settings
        """
        self.config_parser = ConfigParser(name="DesignerSettings")
        DESIGNER_CONFIG = os.path.join(get_kivy_designer_dir(), DESIGNER_CONFIG_FILE_NAME)

        _dir = os.path.dirname(designer.__file__)
        _dir = os.path.split(_dir)[0]

        DEFAULT_CONFIG = os.path.join(_dir, DESIGNER_CONFIG_FILE_NAME)
        if not os.path.exists(DESIGNER_CONFIG):
            shutil.copyfile(DEFAULT_CONFIG, DESIGNER_CONFIG)

        self.config_parser.read(DESIGNER_CONFIG)
        self.config_parser.upgrade(DEFAULT_CONFIG)

        # creates a panel before insert it to update code input theme list
        panel = self.create_json_panel(
            "Kivy Designer Settings",
            self.config_parser,
            os.path.join(_dir, "designer", "settings", "designer_settings.json"),
        )
        uid = panel.uid
        if self.interface is not None:
            self.interface.add_panel(panel, "Kivy Designer Settings", uid)

        # loads available themes
        for child in panel.children:
            if child.id == "code_input_theme_options":
                child.items = styles.get_all_styles()

        # tries to find python and buildozer path if it's not defined
        path = self.config_parser.getdefault("global", "python_shell_path", "")

        if path.strip() == "":
            self.config_parser.set("global", "python_shell_path", sys.executable)
            self.config_parser.write()

        buildozer_path = self.config_parser.getdefault("buildozer", "buildozer_path", "")

        if buildozer_path.strip() == "":
            buildozer_path = find_executable("buildozer")
            if buildozer_path:
                self.config_parser.set("buildozer", "buildozer_path", buildozer_path)
                self.config_parser.write()

        self.add_json_panel(
            "Buildozer", self.config_parser, os.path.join(_dir, "designer", "settings", "buildozer_settings.json")
        )
        self.add_json_panel(
            "Hanga", self.config_parser, os.path.join(_dir, "designer", "settings", "hanga_settings.json")
        )
        self.add_json_panel(
            "Keyboard Shortcuts", self.config_parser, os.path.join(_dir, "designer", "settings", "shortcuts.json")
        )

    def on_config_change(self, *args):
        """This function is default handler of on_config_change event.
        """
        self.config_parser.write()
        super(DesignerSettings, self).on_config_change(*args)
开发者ID:Lh4cKg,项目名称:kivy-designer,代码行数:78,代码来源:designer_settings.py

示例10: Program

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]

#.........这里部分代码省略.........
            core.string_lang_setting_mail_desc,
            core.string_lang_setting_mail_interval_title,
            core.string_lang_setting_mail_interval_desc)

        theme_settings = open("{}/Data/Settings/theme.json".format(
            core.prog_path)).read()
        theme_data = theme_settings % (
            core.string_lang_setting_chek_themes,
            core.string_lang_setting_chek_themes_title,
            core.string_lang_setting_chek_themes_desc,
            '", "'.join(os.listdir("{}/Data/Themes".format(core.prog_path))),
            core.string_lang_setting_edit_themes_title,
            core.string_lang_setting_edit_themes_desc,
            core.string_lang_setting_create_themes_title,
            core.string_lang_setting_create_themes_desc)

        settings.add_json_panel(core.string_lang_general,
                                self.config, data=general_data)
        settings.add_json_panel(core.string_lang_internet,
                                self.config, data=network_data)
        settings.add_json_panel(core.string_lang_mail[:-1],
                                self.config, data=mail_data)
        settings.add_json_panel(core.string_lang_theme,
                                self.config, data=theme_data)

    def on_config_change(self, config, section, key, value):
        """Вызывается при выборе одного из пункта настроек программы."""

        def select_callback(*args):
            file_manager.body.dismiss()
            self.downloadfolder[1] = file_manager.select_folder
            config.set("General", "downloadkey", "1")
            config.set("General", "downloadfolder", str(self.downloadfolder))
            config.write()

        # TODO: обновить описание раздела на путь к выбранной директориии.
        if key == "downloadkey" and int(value):  # "Настройки загрузок"
            file_manager = \
                FileChooser(select_callback=select_callback, filter="folder",
                            title=core.string_lang_select_folder,
                            background_image=self.core.theme_decorator_window,
                            auto_dismiss=False,  size=(.85, .9),)
        elif key == "downloadkey" and not int(value):
            self.downloadfolder[1] = ""
            config.set("General", "downloadkey", "0")
            config.set("General", "downloadfolder", str(self.downloadfolder))
            config.write()
        elif key == "checkattachtoforum":  # "Проверка формы аттача"
            self.checkattachtoforum = int(value)
        elif key == "progresstextsize":  # "Настойка размера шрифта"
            self.window_text_size = int(value)
        elif key == "edittheme":  # "Правка палитры установленной темы"
            self.edit_pallete_theme()

    def on_pause(self):
        """Ставит приложение на 'паузу' при выхоже из него.
        В противном случае запускает программу по заново"""

        return True

    def build(self):
        self.title = core.string_lang_title[:-1]  # заголовок окна программы
        self.icon = "Data/Images/logo.png"  # иконка окна программы
        self.use_kivy_settings = False

        self.config = ConfigParser()
开发者ID:HeaTTheatR,项目名称:HeaTDV4A,代码行数:70,代码来源:program.py

示例11: UserPrefs

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]

#.........这里部分代码省略.........

    def set_dashboard_screens(self, screens):
        self._prefs_dict['screens'] = copy(screens)
        self.save()

# Regular preferences below here

    def get_last_selected_track_id(self):
        return self.get_pref('track_detection', 'last_selected_track_id')

    def get_last_selected_track_timestamp(self):
        return self.get_pref_int('track_detection', 'last_selected_track_timestamp')

    def get_user_cancelled_location(self):
        return self.get_pref('track_detection', 'user_cancelled_location')

    def set_last_selected_track(self, track_id, timestamp, user_cancelled_location='0,0'):
        self.set_pref('track_detection', 'last_selected_track_id', track_id)
        self.set_pref('track_detection', 'last_selected_track_timestamp', timestamp)
        self.set_pref('track_detection', 'user_cancelled_location', user_cancelled_location)
        self.save()

    @property
    def datastore_location(self):
        return os.path.join(self.data_dir, 'datastore.sq3')

    def save(self, *largs):
        '''
        Saves the current configuration
        '''
        Logger.info('UserPrefs: Saving preferences')
        with open(self.prefs_file, 'w+') as prefs_file:
            data = self.to_json()
            prefs_file.write(data)

    def set_config_defaults(self):
        '''
        Set defaults for preferences 
        '''
        # Base system preferences
        self.config.adddefaultsection('help')
        self.config.adddefaultsection('preferences')
        self.config.setdefault('preferences', 'distance_units', 'miles')
        self.config.setdefault('preferences', 'temperature_units', 'Fahrenheit')
        self.config.setdefault('preferences', 'show_laptimes', 1)
        self.config.setdefault('preferences', 'startup_screen', 'Home Page')
        default_user_files_dir = self.user_files_dir
        self.config.setdefault('preferences', 'config_file_dir', default_user_files_dir)
        self.config.setdefault('preferences', 'export_file_dir', default_user_files_dir)
        self.config.setdefault('preferences', 'firmware_dir', default_user_files_dir)
        self.config.setdefault('preferences', 'import_datalog_dir', default_user_files_dir)
        self.config.setdefault('preferences', 'send_telemetry', '0')
        self.config.setdefault('preferences', 'record_session', '1')
        self.config.setdefault('preferences', 'global_help', True)

        # Connection type for mobile
        if is_mobile_platform():
            if is_android():
                self.config.setdefault('preferences', 'conn_type', 'Bluetooth')
            elif is_ios():
                self.config.setdefault('preferences', 'conn_type', 'WiFi')
        else:
            self.config.setdefault('preferences', 'conn_type', 'Serial')

        # Dashboard preferences
        self.config.adddefaultsection('dashboard_preferences')
开发者ID:autosportlabs,项目名称:RaceCapture_App,代码行数:70,代码来源:prefs.py

示例12: UserPrefs

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class UserPrefs(EventDispatcher):
    '''
    A class to manage user preferences for the RaceCapture app
    '''
    _schedule_save = None
    _prefs_dict = {'range_alerts': {}, 'gauge_settings':{}}
    store = None
    prefs_file_name = 'prefs.json'
    prefs_file = None
    config = None
    data_dir = '.'
    user_files_dir = '.'

    def __init__(self, data_dir, user_files_dir, save_timeout=2, **kwargs):
        self.data_dir = data_dir
        self.user_files_dir = user_files_dir
        self.prefs_file = path.join(self.data_dir, self.prefs_file_name)
        self.load()
        self._schedule_save = Clock.create_trigger(self.save, save_timeout)

    def set_range_alert(self, key, range_alert):
        '''
        Sets a range alert with the specified key
        :param key the key for the range alert
        :type string
        :param range_alert the range alert
        :type object
        '''
        self._prefs_dict["range_alerts"][key] = range_alert
        self._schedule_save()

    def get_range_alert(self, key, default=None):
        '''
        Retrives a range alert for the specified key
        :param key the key for the range alert
        :type key string
        :param default the default value, optional
        :type default user specified
        :return the range alert, or the default value 
        '''
        return self._prefs_dict["range_alerts"].get(key, default)

    def set_gauge_config(self, gauge_id, channel):
        '''
        Stores a gauge configuration for the specified gauge_id
        :param gauge_id the key for the gauge
        :type gauge_id string
        :param channel the configuration for the channel
        :type channel object
        '''
        self._prefs_dict["gauge_settings"][gauge_id] = channel
        self._schedule_save()

    def get_gauge_config(self, gauge_id):
        '''
        Get the gauge configuration for the specified gauge_id
        :param gauge_id the key for the gauge
        :type string
        :return the gauge configuration
        '''
        return self._prefs_dict["gauge_settings"].get(gauge_id, False)

    def get_last_selected_track_id(self):
        return self.get_pref('track_detection', 'last_selected_track_id')

    def get_last_selected_track_timestamp(self):
        return self.get_pref_int('track_detection', 'last_selected_track_timestamp')

    def set_last_selected_track(self, track_id, timestamp):
        self.set_pref('track_detection', 'last_selected_track_id', track_id)
        self.set_pref('track_detection', 'last_selected_track_timestamp', timestamp)

    @property
    def datastore_location(self):
        return os.path.join(self.data_dir, 'datastore.sq3')

    def save(self, *largs):
        '''
        Saves the current configuration
        '''
        with open(self.prefs_file, 'w+') as prefs_file:
            data = self.to_json()
            prefs_file.write(data)

    def set_config_defaults(self):
        '''
        Set defaults for preferences 
        '''
        # Base system preferences
        self.config.adddefaultsection('help')
        self.config.adddefaultsection('preferences')
        self.config.setdefault('preferences', 'distance_units', 'miles')
        self.config.setdefault('preferences', 'temperature_units', 'Fahrenheit')
        self.config.setdefault('preferences', 'show_laptimes', 1)
        self.config.setdefault('preferences', 'startup_screen', 'Home Page')
        default_user_files_dir = self.user_files_dir
        self.config.setdefault('preferences', 'config_file_dir', default_user_files_dir)
        self.config.setdefault('preferences', 'firmware_dir', default_user_files_dir)
        self.config.setdefault('preferences', 'import_datalog_dir', default_user_files_dir)
        self.config.setdefault('preferences', 'first_time_setup', '1')
#.........这里部分代码省略.........
开发者ID:ddimensia,项目名称:RaceCapture_App,代码行数:103,代码来源:prefs.py

示例13: UserPrefs

# 需要导入模块: from kivy.config import ConfigParser [as 别名]
# 或者: from kivy.config.ConfigParser import write [as 别名]
class UserPrefs(EventDispatcher):
    _schedule_save = None
    _prefs_dict = {'range_alerts': {}, 'gauge_settings':{}}
    store = None
    prefs_file_name = 'prefs.json'
    prefs_file = None
    config = None
    data_dir = '.'
    user_files_dir = '.'

    def __init__(self, data_dir, user_files_dir, save_timeout=2, **kwargs):
        self.data_dir = data_dir
        self.user_files_dir = user_files_dir
        self.prefs_file = path.join(self.data_dir, self.prefs_file_name)
        self.load()
        self._schedule_save = Clock.create_trigger(self.save, save_timeout)

    def set_range_alert(self, key, range_alert):
        self._prefs_dict["range_alerts"][key] = range_alert
        self._schedule_save()
        
    def get_range_alert(self, key, default=None):
        return self._prefs_dict["range_alerts"].get(key, default)

    def set_gauge_config(self, gauge_id, channel):
        self._prefs_dict["gauge_settings"][gauge_id] = channel
        self._schedule_save()

    def get_gauge_config(self, gauge_id):
        return self._prefs_dict["gauge_settings"].get(gauge_id, False)

    def save(self, *largs):
        with open(self.prefs_file, 'w+') as prefs_file:
            data = self.to_json()
            prefs_file.write(data)

    def set_config_defaults(self):
        self.config.adddefaultsection('preferences')
        self.config.setdefault('preferences', 'distance_units', 'miles')
        self.config.setdefault('preferences', 'temperature_units', 'Fahrenheit')
        self.config.setdefault('preferences', 'show_laptimes', 1)
        self.config.setdefault('preferences', 'startup_screen', 'Home Page')
        default_user_files_dir = self.user_files_dir
        self.config.setdefault('preferences', 'config_file_dir', default_user_files_dir )
        self.config.setdefault('preferences', 'firmware_dir', default_user_files_dir )
        self.config.setdefault('preferences', 'first_time_setup', True)
        self.config.setdefault('preferences', 'send_telemetry', False)
        self.config.setdefault('preferences', 'last_dash_screen', 'gaugeView')

    def load(self):
        print("the data dir " + self.data_dir)
        self.config = ConfigParser()
        self.config.read(os.path.join(self.data_dir, 'preferences.ini'))
        self.set_config_defaults()

        self._prefs_dict = {'range_alerts': {}, 'gauge_settings':{}}

        try:
            with open(self.prefs_file, 'r') as data:
                content = data.read()
                content_dict = json.loads(content)

                if content_dict.has_key("range_alerts"):
                    for name, settings in content_dict["range_alerts"].iteritems():
                        self._prefs_dict["range_alerts"][name] = Range.from_dict(settings)

                if content_dict.has_key("gauge_settings"):
                    for id, channel in content_dict["gauge_settings"].iteritems():
                        self._prefs_dict["gauge_settings"][id] = channel

        except Exception:
            pass
        
    def get_pref(self, section, option):
        return self.config.get(section, option)
    
    def set_pref(self, section, option, value):
        self.config.set(section, option, value)
        self.config.write()

    def to_json(self):
        data = {'range_alerts': {}, 'gauge_settings':{}}

        for name, range_alert in self._prefs_dict["range_alerts"].iteritems():
            data["range_alerts"][name] = range_alert.to_dict()

        for id, channel in self._prefs_dict["gauge_settings"].iteritems():
            data["gauge_settings"][id] = channel

        return json.dumps(data)
开发者ID:aishwaryaMandyam,项目名称:RaceCapture_App,代码行数:92,代码来源:prefs.py


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