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


Python ConfigParser.read方法代码示例

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


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

示例1: testUnicodeFileName

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
 def testUnicodeFileName(self):
     """
     Should be able to write to unicode filenames
     """
     # Invent a unicode filename
     dirName = unicode('\xc4\x80\xc4\x900', 'utf8')
     fn = os.path.join(dirName, dirName)
     fn += '.ini'
     if not os.path.exists(dirName):
         os.mkdir(dirName)
     # Write some test data to our unicode file
     file_ = open(fn, 'wb')
     file_.write(TEST_TEXT)
     file_.close()
     # See if we can read and write it
     self.c.read(fn)
     self.assertEquals(self.c.main.power, 'on')
     self.c.main.power = 'off'
     self.c.write()
     # Check that it was written ok
     c2 = ConfigParser()
     c2.read(fn)
     self.assertEquals(c2.main.power, 'off')
     # Clean up
     os.remove(fn)
     os.rmdir(dirName)
开发者ID:,项目名称:,代码行数:28,代码来源:

示例2: testUpgradeAppDir

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
 def testUpgradeAppDir(self):
     """
     Tests that config files with
     'appDataDir' are upgraded to 'configDir'
     """
     # Write the old style config file
     configPath = Path(u'test.exe.conf')
     if configPath.exists():
         configPath.remove()
     oldParser = ConfigParser()
     system = oldParser.addSection('system')
     system.appDataDir = 'my old app data dir'
     oldParser.write(configPath)
     del system
     del oldParser
     # Make the config instance load it
     Config._getConfigPathOptions = lambda self: ['test.exe.conf']
     myconfig = Config()
     myconfig.loadSettings()
     # Check if it reads the old value into the new variable
     assert not hasattr(myconfig, 'appDataDir')
     self.assertEquals(myconfig.configPath, 'test.exe.conf')
     self.assertEquals(myconfig.configDir, 'my old app data dir')
     # Check if it has upgraded the file and added in some nice default values
     newParser = ConfigParser()
     newParser.read(configPath)
     self.assertEquals(newParser.system.configDir, 'my old app data dir')
开发者ID:KatiaBorges,项目名称:exeLearning,代码行数:29,代码来源:testconfig.py

示例3: testStringIO

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
 def testStringIO(self):
     file_ = testFile()
     c = ConfigParser()
     c.read(file_)
     c.autoWrite = True
     assert 'Matthew' not in self.getVal(file_)
     c.main.name = 'Matthew'
     assert 'name = Matthew' in self.getVal(file_), self.getVal(file_)
     del c.main.name
     assert 'Matthew' not in self.getVal(file_)
开发者ID:,项目名称:,代码行数:12,代码来源:

示例4: testShortening

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
 def testShortening(self):
     """There was a bug (Issue 66) where when a longer name was read
     and a shorter name was written, the extra characters of the 
     longer name would remain in the entry"""
     file_ = open('temp.ini', 'w')
     file_.write(TEST_TEXT)
     file_.close()
     self.c.read('temp.ini')
     self.c.set('second', 'available', 'abcdefghijklmnop')
     self.c.write('temp.ini')
     c2 = ConfigParser()
     c2.read('temp.ini')
     c2.set('second', 'available', 'short')
     c2.write('temp.ini')
     self.c.read('temp.ini')
     assert self.c.get('second', 'available', '') == 'short', \
         self.c.get('second', 'available', '')
开发者ID:,项目名称:,代码行数:19,代码来源:

示例5: testUnicodeSet

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
 def testUnicodeSet(self):
     """
     Should be able to set unicode option values
     with both python internal unicode strings
     or raw string containing utf8 encoded data
     """
     file_ = open('temp.ini', 'w')
     file_.write(TEST_TEXT)
     file_.close()
     self.c.read('temp.ini')
     self.c.set('main', 'power', '\xc4\x80\xc4\x900')
     self.c.set('main', 'name', unicode('\xc4\x80\xc4\x900', 'utf8'))
     self.c.set('newSecy', 'unicode', unicode('\xc4\x80\xc4\x900', 'utf8'))
     self.c.write('temp.ini')
     c2 = ConfigParser()
     c2.read('temp.ini')
     val = unicode('\xc4\x80\xc4\x900', 'utf8')
     self.assertEquals(c2.main.power, val)
     self.assertEquals(c2.main.name, val)
     self.assertEquals(c2.newSecy.unicode, val)
开发者ID:,项目名称:,代码行数:22,代码来源:

示例6: Config

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
class Config(object):
    """
    The Config class contains the configuration information for eXe.
    """

    # To build link to git revision
    baseGitWebURL = 'https://forja.cenatic.es/plugins/scmgit/cgi-bin/gitweb.cgi?p=iteexe/iteexe.git'

    # Class attributes
    optionNames = {
        'system': ('webDir', 'jsDir', 'port', 'dataDir',
                   'configDir', 'localeDir', 'browser', 'mediaProfilePath',
                   'videoMediaConverter_ogv', 'videoMediaConverter_3gp',
                   'videoMediaConverter_mpg',
                   'videoMediaConverter_avi', 'audioMediaConverter_ogg',
                   'audioMediaConverter_au', 'audioMediaConverter_mp3',
                   'audioMediaConverter_wav', 'ffmpegPath'),
        'user': ('locale', 'lastDir', 'showPreferencesOnStart','defaultStyle', 'showIdevicesGrouped','docType','editorMode'),
    }

    idevicesCategories = {
        'activity': [x_('Non-Interactive Activities')],
        'reading activity': [x_('Non-Interactive Activities')],
        'dropdown activity': [x_('Interactive Activities')],
        'java applet': [x_('Non-Textual Information')],
        'wiki article': [x_('Non-Textual Information')],
        'case study': [x_('Non-Interactive Activities')],
        'preknowledge': [x_('Textual Information')],
        'scorm quiz': [x_('Interactive Activities')],
        'fpd - multi choice activity': [x_('FPD')],
        'fpd - cloze activity': [x_('FPD')],
        'fpd - cloze activity (modified)': [x_('FPD')],
        'fpd - multi select activity': [x_('FPD')],
        'fpd - true/false activity': [x_('FPD')],
        'fpd - situation': [x_('FPD')],
        'fpd - quotation': [x_('FPD')],
        'fpd - you should know': [x_('FPD')],
        'fpd - highlighted': [x_('FPD')],
        'fpd - translation': [x_('FPD')],
        'fpd - guidelines students': [x_('FPD')],
        'fpd - guidelines teacher': [x_('FPD')],
        'fpd - a step ahead': [x_('FPD')],
        'fpd - a piece of advice': [x_('FPD')],
        'fpd - think about it (with feedback)': [x_('FPD')],
        'fpd - think about it (without feedback)': [x_('FPD')],
        'fpd - free text': [x_('FPD')],
        'image gallery': [x_('Non-Textual Information')],
        'image magnifier': [x_('Non-Textual Information')],
        'note': [x_('Textual Information')],
        'objectives': [x_('Textual Information')],
        'multi-choice': [x_('Interactive Activities')],
        'multi-select': [x_('Interactive Activities')],
        'true-false question': [x_('Interactive Activities')],
        'reflection': [x_('Non-Interactive Activities')],
        'cloze activity': [x_('Interactive Activities')],
        'rss': [x_('Non-Textual Information')],
        'external web site': [x_('Non-Textual Information')],
        'free text': [x_('Textual Information')],
        'click in order game': [x_('Experimental')],
        'hangman game': [x_('Experimental')],
        'place the objects': [x_('Interactive Activities')],
        'memory match game': [x_('Experimental')],
        'file attachments': [x_('Non-Textual Information')],
        'sort items': [x_('Experimental')],
        'sort items': [x_('Interactive Activities')],
        'scorm test cloze': [x_('Interactive Activities')],
        'scorm test cloze (multiple options)': [x_('Interactive Activities')],
        'scorm test dropdown': [x_('Interactive Activities')],
        'scorm test multiple choice': [x_('Interactive Activities')]
    }
    
    @classmethod
    def getConfigPath(cls):
        obj = cls.__new__(cls)
        obj.configParser = ConfigParser()
        obj._overrideDefaultVals()
        obj.__setConfigPath()
        return obj.configPath

    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser(self.onWrite)
        # Set default values
        # exePath is the whole path and filename of the exe executable
        self.exePath     = Path(sys.argv[0]).abspath()
        # webDir is the parent directory for styles,scripts and templates
        self.webDir      = self.exePath.dirname()
        self.jsDir       = self.exePath.dirname()
        # localeDir is the base directory where all the locales are stored
        self.localeDir   = self.exePath.dirname()/"locale"
        # port is the port the exe webserver will listen on 
        # (previous default, which earlier users might still use, was 8081)
        self.port        = 51235
        # dataDir is the default directory that is shown to the user
        # to save packages and exports in
        self.dataDir     = Path(".")
        # configDir is the dir for storing user profiles
#.........这里部分代码省略.........
开发者ID:kohnle-lernmodule,项目名称:exe201based,代码行数:103,代码来源:config.py

示例7: __init__

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
class Config:
    """
    The Config class contains the configuration information for eXe.
    """

    optionNames = {
        "system": ("webDir", "xulDir", "port", "dataDir", "configDir", "localeDir", "browserPath"),
        "user": ("locale",),
    }

    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser()
        self.exePath = Path(sys.argv[0]).abspath()
        self.webDir = self.exePath.dirname()
        self.xulDir = self.exePath.dirname()
        self.localeDir = self.exePath.dirname() / "locale"
        self.port = 51235
        self.dataDir = Path(".")
        self.configDir = Path(".")
        self.browserPath = Path("firefox")
        self.locale = chooseDefaultLocale(self.localeDir)
        self.styles = []
        self._overrideDefaultVals()
        self.webDir = Path(self.webDir)
        if not (self.webDir / "scripts").isdir() and (self.webDir / "webui").isdir():
            self.webDir /= "webui"
        self.xulDir = Path(self.xulDir)
        if not (self.xulDir / "scripts").isdir() and (self.xulDir / "xului").isdir():
            self.xulDir /= "xului"
        self.__setConfigPath()
        self._writeDefaultConfigFile()
        self.loadSettings()
        self.setupLogging()
        self.loadStyles()
        self.loadLocales()

    def _overrideDefaultVals(self):
        """
        Override this to override the
        default config values
        """

    def _getConfigPathOptions(self):
        """
        Override this to give a list of
        possible config filenames
        in order of preference
        """
        return ["exe.conf"]

    def _writeDefaultConfigFile(self):
        """
        [Over]writes 'self.configPath' with a default config file 
        (auto write is on so we don't need to write the file at the end)
        """
        for sectionName, optionNames in self.optionNames.items():
            for optionName in optionNames:
                defaultVal = getattr(self, optionName)
                self.configParser.setdefault(sectionName, optionName, defaultVal)
        self.configParser.setdefault("logging", "root", "INFO")

    def __setConfigPath(self):
        """
        sets self.configPath to the filename of the config file that we'll
        use.
        In descendant classes set self.configFileOptions to a list
        of directories where the configDir should be in order of preference.
        If no config files can be found in these dirs, it will
        force creation of the config file in the top dir
        """
        self.configPath = None
        configFileOptions = map(Path, self._getConfigPathOptions())
        if "EXECONF" in os.environ:
            envconf = Path(os.environ["EXECONF"])
            if envconf.isfile():
                self.configPath = os.environ["EXECONF"]
        if self.configPath is None:
            for confPath in configFileOptions:
                if confPath.isfile():
                    self.configPath = confPath
                    break
            else:
                self.configPath = configFileOptions[0]
                folder = self.configPath.abspath().dirname()
                if not folder.exists():
                    folder.makedirs()
                self.configPath.touch()
        self.configParser.read(self.configPath)
        self.configParser.autoWrite = True

    def upgradeFile(self):
        """
        Called before loading the config file,
        removes or upgrades any old settings.
        """
        if self.configParser.has_section("system"):
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例8: __init__

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]

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

        
    def __setConfigPath(self):
        """
        sets self.configPath to the filename of the config file that we'll
        use.
        In descendant classes set self.configFileOptions to a list
        of directories where the configDir should be in order of preference.
        If no config files can be found in these dirs, it will
        force creation of the config file in the top dir
        """
        # If there's an EXECONF environment variable, use it
        self.configPath = None
        configFileOptions = map(Path, self._getConfigPathOptions())
        if "EXECONF" in os.environ:
            envconf = Path(os.environ["EXECONF"])
            if envconf.isfile():
                self.configPath = os.environ["EXECONF"]
        # Otherwise find the most appropriate existing file
        if self.configPath is None:
            for confPath in configFileOptions:
                if confPath.isfile():
                    self.configPath = confPath
                    break
            else:
                # If no config files exist, create and use the
                # first one on the list
                self.configPath = configFileOptions[0]
                folder = self.configPath.abspath().dirname()
                if not folder.exists():
                    folder.makedirs()
                self.configPath.touch()
        # Now make our configParser
        self.configParser.read(self.configPath)
        self.configParser.autoWrite = True


    def upgradeFile(self):
        """
        Called before loading the config file,
        removes or upgrades any old settings.
        """
        if self.configParser.has_section('system'):
            system = self.configParser.system
            if system.has_option('appDataDir'):
                # Older config files had configDir stored as appDataDir
                self.configDir = Path(system.appDataDir)
                # We'll just upgrade their config file for them for now...
                system.configDir = self.configDir
                del system.appDataDir
            if system.has_option('greDir'):
                # No longer used, system should automatically support
                del system.greDir


    def loadSettings(self):
        """
        Loads the settings from the exe.conf file.
        Overrides the defaults set in __init__
        """
        # Set up the parser so that if a certain value is not in the config
        # file, it will use the value from our default values
        def defVal(dummy, option):
            """If something is not in the config file, just use the default in
            'self'"""
            return getattr(self, option)
开发者ID:KatiaBorges,项目名称:exeLearning,代码行数:70,代码来源:config.py

示例9: TestConfigParser

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
class TestConfigParser(unittest.TestCase):
    """
    Tests the main ConfigParser class
    """

    def setUp(self):
        """
        Creates a ConfigParser to play with
        """
        self.c = ConfigParser()

    def testRead(self):
        """Ensures that it can read from a file correctly"""
        file_ = testFile()
        self.c.read(file_)
        assert self.c._sections == {'second':
                                       {'good': 'yes',
                                        'bad': 'no',
                                         'available': 'yes',
                                         'funny-name_mate': 'crusty the clown'}, 
                                    'main': 
                                        {'running': u'on\t\u0100\u01100',
                                         'testing': 'false',
                                         'two words': 'are better than one',
                                         'no_value': '',
                                         'power': 'on', 'level': '5'}
                                    }, self.c._sections

    def testReadFileName(self):
        """Can read text"""
        goodDict = {'second': 
                        {'good': 'yes',
                         'bad': 'no',
                          'available': 'yes',
                          'funny-name_mate': 'crusty the clown'}, 
                    'main': 
                        {'running': u'on\t\u0100\u01100',
                         'testing': 'false',
                         'two words': 'are better than one',
                         'no_value': '',
                         'power': 'on',
                         'level': '5'}}
        file_ = open('temp.ini', 'w')
        file_.write(TEST_TEXT)
        file_.close()
        self.c.read('temp.ini')
        assert self.c._sections == goodDict, self.c._sections
        # Can read unicode filenames
        self.c = ConfigParser()
        self.c.read(u'temp.ini')
        assert self.c._sections == goodDict, self.c._sections
        # Can read funny string object filenames
        class MyStr(str):
            """Simply overrides string to make it a different type"""
        self.c.read(MyStr('temp.ini'))
        assert self.c._sections == goodDict, self.c._sections

    def testWrite(self):
        """Test that it writes the file nicely"""
        file_ = testFile()
        self.c.read(file_)
        # Remove an option
        del self.c._sections['main']['testing']
        # Change an option
        self.c._sections['second']['bad'] = 'definately not!   '
        # Add an option
        self.c._sections['second']['squishy'] = 'Indeed'
        # Add a section at the end
        self.c._sections['middle'] = {'is here': 'yes'}
        # write the file
        file_.seek(0)
        self.c.write(file_)
        file_.seek(0)
        result = file_.readlines()
        result = map(unicode, result, ['utf8']*len(result))
        goodResult = ['nosection=here\n',
                      '[main]\n',
                      'level=5\n',
                      'power : on\n',
                      u'running =on\t\u0100\u01100\n',
                      'two words = \tare better than one\n',
                      'no_value = \n',
                      '\n', '\n',
                      '[second]\n',
                      'good :yes\n',
                      'bad:\tdefinately not!   \n',
                      '# comment=1\n',
                      '~comment2=2\n',
                      'available\t=   yes\n',
                      'funny-name_mate: crusty the clown\n',
                      'squishy = Indeed\n',
                      '\n',
                      '[middle]\n',
                      'is here = yes']
        if result != goodResult:
            print
            for good, got in zip(goodResult, result):
                if good != got:
                    print 'Different', repr(good), repr(got)
            self.fail('See above printout')
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:

示例10: TestSections

# 需要导入模块: from exe.engine.configparser import ConfigParser [as 别名]
# 或者: from exe.engine.configparser.ConfigParser import read [as 别名]
class TestSections(unittest.TestCase):
    """
    Tests Section objects.
    Section objects allow an easy way to read and write
    """

    def setUp(self):
        """
        Creates a ConfigParser to play with and
        reads in the test text
        """
        self.c = ConfigParser()
        file_ = testFile()
        self.c.read(file_)

    def testSectionCreation(self):
        """
        Tests that the configuration object
        creates the section objects ok
        """
        assert isinstance(self.c.main, Section)
        assert isinstance(self.c.second, Section)
        self.failUnlessRaises(AttributeError, lambda: self.c.notexist)

    def testFromScratch(self):
        """
        Tests adding stuff from nothing
        """
        x = ConfigParser()
        testing = x.addSection('testing')
        assert x.testing is testing
        testing.myval = 4
        self.assertEquals(x.get('testing', 'myval'), '4')

    def testAttributeRead(self):
        """
        Tests that we can read attributes from sections
        """
        assert self.c.main.level == '5'
        assert self.c.main.power == 'on'
        self.failUnlessRaises(AttributeError, lambda: self.c.main.notexist)

    def testAttributeWrite(self):
        """
        Tests that we can set attributes with sections
        """
        self.c.main.level = 7
        # Should be automatically converted to string also :)
        self.assertEquals(self.c.get('main', 'level'), '7')
        self.c.main.new = 'hello'
        assert self.c.get('main', 'new') == 'hello'

    def testAttributeDel(self):
        """
        Tests that we can remove attributes from the config file
        by removing the sections
        """
        del self.c.main.level
        assert not self.c.has_option('main', 'level')

    def testSectionDel(self):
        """
        Tests that we can remove whole sections
        by deleting them
        """
        del self.c.main
        assert not self.c.has_section('main')
        def delete(): del self.c.notexist
        self.failUnlessRaises(AttributeError, delete)

    def testParserIn(self):
        """
        To test if a section exists, use the in operator
        """
        assert 'main' in self.c
        assert 'notexist' not in self.c
        # Dotted format
        assert 'main.level' in self.c
        assert 'main.notexist' not in self.c
        # And the sections can do it too
        assert 'notexist' not in self.c.main
        # Also the hasattr should give the same result
        assert hasattr(self.c, 'main')
        assert not hasattr(self.c, 'notexist')
        assert hasattr(self.c, 'main.level')
        assert hasattr(self.c.main, 'level')
        assert not hasattr(self.c.main, 'notexist')

    def testGet(self):
        """
        System should have a get section for those funny
        names that can't be attributes
        """
        assert self.c.second.get('funny-name_mate') == 'crusty the clown'

    def testCreation(self):
        """
        When one creates a section with the same name
        as an existing section the existing section should
        just be returned
#.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:103,代码来源:


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