Уведомления

Группа в Telegram: @pythonsu

#1 Авг. 9, 2016 18:07:47

Guljaca
От:
Зарегистрирован: 2011-07-11
Сообщения: 93
Репутация: +  0  -
Профиль   Отправить e-mail  

config parser ошибка при чтении

В скрипте ниже должны записываться данные из файла конфигурации в словарь классов. Проблема в том, что в результате во всех классах прописываются данные из последней секции.

N=q

N=y
В обоих классах в данных пропишется N=y

[code python]  import ConfigParser, os

def absolutepath(opfile):
config = ConfigParser.SafeConfigParser()
scriptDirectory = os.path.dirname(os.path.realpath(__file__))
settingsFilePath = os.path.join(scriptDirectory, opfile)
config.readfp(open(settingsFilePath,"r"))
return config
print 'import', opfile

def writedata(ndict,nclass,namefile):
opfile=absolutepath(namefile)
for section in opfile.sections():
ndict[section]=nclass
for option in opfile.options(section):
ndict[section].options[option]=opfile.get(section,option)
print section,ndict[section].options [/code]



Офлайн

#2 Авг. 10, 2016 02:10:30

terabayt
От: Киев
Зарегистрирован: 2011-11-26
Сообщения: 1099
Репутация: +  103  -
Профиль   Отправить e-mail  

config parser ошибка при чтении

я предполагаю что вы в функцию writedata параметром nclass передаете объект (экземпляр класса)
это тоже самое если бы вы делали так

 def writedata(ndict,nclass,namefile):
    opfile=absolutepath(namefile)
    for section in opfile.sections():
            for option in opfile.options(section):
                nclass.options[option]=opfile.get(section,option)
            print section,nclass.options
а если вы хотите
Guljaca
должны записываться данные из файла конфигурации в словарь классов
то нужно так
 # . . .
class A:
    # . . .
def writedata(ndict,nclass,namefile):
    opfile=absolutepath(namefile)
    for section in opfile.sections():
            ndict[section]=nclass()
            for option in opfile.options(section):
                ndict[section].options[option]=opfile.get(section,option)
            print section,ndict[section].options 
writedata({}, A, ‘namefile.txt’)


вот пример
так делаете вы
 class A:
    def __init__(self):
        self.options = {}
ndict = {}
def f(d, c):
    for i in range(3):
        d[i] = c
        for j in range(i, 5):
            d[i].options[j] = j*2-i
    return d
t = f(ndict, A())
for i, j in t.items():
    print(i, j.options)
0 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
1 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
2 {0: 0, 1: 1, 2: 2, 3: 4, 4: 6}
а так нужно
 class A:
    def __init__(self):
        self.options = {}
ndict = {}
def f(d, c):
    for i in range(3):
        d[i] = c()  # с скобками
        for j in range(i, 5):
            d[i].options[j] = j*2-i
    return d
t = f(ndict, A)  # без скобок
for i, j in t.items():
    print(i, j.options)
0 {0: 0, 1: 2, 2: 4, 3: 6, 4: 8}
1 {1: 1, 2: 3, 3: 5, 4: 7}
2 {2: 2, 3: 4, 4: 6}



————————————————
-*- Simple is better than complex -*-

Отредактировано terabayt (Авг. 10, 2016 02:11:30)

Офлайн

Board footer

Модераторировать

Powered by DjangoBB

Lo-Fi Version