Domanda

A little bit about the code; what I'm trying to do is turning a section into a Dict so I can easily manage it. Of course, because ConfigParser returns everything as a string (most of the time anyway), I have to change it into the desired type. And that's where my problem starts.

Code

import ConfigParser, pygame

parser = ConfigParser.SafeConfigParser()

class loadfile(object):

    def __init__(self, filename):
        self.filename = filename

    def load(self):
        parser.read(self.filename)

        for section_name in parser.sections():
            vars()[section_name] = {}

            for name, value in parser.items(section_name):
                if value.isdigit():
                    value = int(value)
                elif value == "None":
                    value = None
                elif value == "True" or value == "False":
                    value = parser.getboolean( section_name, name )
                else:
                    value = vars()[ parser.get( section_name, name ) ]

                vars()[section_name].update( { name : value } )

            print vars()[section_name]

    def save(self):
        pass

loadfile("config.ini").load()

config.ini

[Display]
Width       : 800
Height      : 600
Depth       : 32
Caption     : 45
Flags       : pygame.RESIZABLE
Icon        : None
Mouse       : True
FPS         : 30

; Key configuration;

[Keys]
Left        : pygame/K_LEFT
Right       : pygame.K_RIGHT
Jump        : pygame.K_UP
Duck        : pygame.K_DOWN
Sprint      : pygame.K_RSHIFT
Attack_1    : pygame.K_a
Attack_2    : pygame.K_s
Attack_3    : pygame.K_d
gameMenu    : pygame.K_ESCAPE
Dialogue    : pygame.K_RETURN

Error

Traceback (most recent call last):
  File "C:\Users\***\Desktop\config2.py", line 35, in <module>
    loadfile("config.ini").load()
  File "C:\Users\***\Desktop\config2.py", line 27, in load
    value = vars()[ parser.get( section_name, name ) ]
KeyError: 'pygame.RESIZABLE'

The same error occurred before I put the code in it's own class, if I used import pygame but it mysteriously went away when I used from pygame import *

È stato utile?

Soluzione

Here's some code that I have written for this, it doesn't use ConfigParser but should work.
(atleast in your case)

class loadfile(object):

    def __init__(self, filename):
        self.filename = filename

    def load(self):
        x = open(self.filename).read()     # open as file and read
        d,k = x.split('; Key configuration;')   # split at Key configration
        d = d.splitlines()
        k = k.splitlines()
        ddict = {}
        for i in d:
                i = i.split(':')
                i = [z.strip() for z in i] # strip whitespace(s)
                if len(i) == 2: # a valid assignment line
                        ddict[i[0]] = i[1] # assignment of value
        #same for keys
        kdict = {}
        for i in k:
                i = i.split(':')
                i = [z.strip() for z in i]
                if len(i) == 2:
                        kdict[i[0]] = i[1]
        print '---Display---'
        for key in kdict:
            print '%10s:%19s' % (key,kdict[key]) # print display part
        print '---Keys---'
        for key in ddict:
            print '%10s:%19s' % (key,ddict[key]) # print key part
        self.kdict = kdict
        self.ddict = ddict
    def save(self):
        pass

x = loadfile("config.ini")
x.load()

Output (from your config.ini)

---Display---
  Attack_1:         pygame.K_a
  Dialogue:    pygame.K_RETURN
     Right:     pygame.K_RIGHT
      Jump:        pygame.K_UP
  Attack_3:         pygame.K_d
  Attack_2:         pygame.K_s
      Duck:      pygame.K_DOWN
    Sprint:    pygame.K_RSHIFT
  gameMenu:    pygame.K_ESCAPE
      Left:      pygame/K_LEFT
---Keys---
   Caption:                 45
    Height:                600
     Width:                800
     Depth:                 32
     Flags:   pygame.RESIZABLE
       FPS:                 30
     Mouse:               True
      Icon:               None

Also, if you use the following type of format for ini file(format may not be the right word), it might be easier to work with.

[Display]
Width=800
Height=600
Depth=32
Caption=45
Flags=pygame.RESIZABLE
Icon=None
Mouse=True
FPS=30
-----
[Keys]
Left=pygame/K_LEFT
Right=pygame.K_RIGHT
Jump=pygame.K_UP
Duck=pygame.K_DOWN
Sprint=pygame.K_RSHIFT
Attack_1=pygame.K_a
Attack_2=pygame.K_s
Attack_3=pygame.K_d
gameMenu=pygame.K_ESCAPE
Dialogue=pygame.K_RETURN
-----

This can be executed(after spliting from '-----', and removing first line of each of these.([keys],[display])

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top