简体   繁体   English

使用Python 2.7和ConfObj / Parser进行麻烦的DAT编辑

[英]Troublesome DAT editing with Python 2.7 and ConfObj/Parser

Edit - final open source code here if interested. 编辑 - 如果感兴趣的话,这里有最终的开源代 https://github.com/qetennyson/ConfigFileBuilder https://github.com/qetennyson/ConfigFileBuilder

Hi there, first question here. 你好,第一个问题在这里。 I'm relatively new to Python (using 2.7 here) and have always been a pretty average programmer as it is. 我对Python比较陌生(在这里使用2.7)并且一直是一个非常普通的程序员。

I'm working on a short program that builds configuration files for these proprietary, internet connected power switches of which I have about 90. Each needs a unique configuration for the city it's going to. 我正在开发一个简短的程序,为这些专有的,互联网连接的电源开关构建配置文件,我有大约90个。每个都需要一个独特的配置,它将要去的城市。

I don't know a ton about filetypes, but these guys are DATs which I figured were similar enough to INI for me to bang my head against the keyboard for six to seven hours, years, eras. 我不知道大量的文件类型,但是这些家伙都是DAT,我认为它与INI类似,让我能够在键盘上敲打六到七个小时,几年。

Here's my existing code. 这是我现有的代码。

from configobj import ConfigObj
import csv
import os

config = ConfigObj('configtest3.dat', list_values=True, raise_errors=False)

with open('config.csv') as csvfile:
    csvreader = csv.reader(csvfile, dialect='excel')
    office = 'null'
    while (office != 'LASTOFFICEINLIST'):
        for row in csvreader:
            config.filename = row[0] + '-powerswitch'
            config['Hostname'] = row[0]
            config['Ipaddr'] = row[2]
            config['OutletName1'] = row[3]
            config['Gateway'] = row[4]
            config['DNS'] = 'DNSTEST'
            config['Account1'] = row[6]
            config['Password1'] = 'passwordtest'
            config['TimeServer1'] = 'x.x.x.x' <--Sanitized
            config['TimeZone'] = '800'
            office = row[0]
            config.write()

You're thinking "that should work fine" and it does, with one exception! 您正在考虑“应该可以正常工作”并且确实如此,只有一个例外!

If I don't remove the "Default" from the beginning of the DAT file (shown here): 如果我不从DAT文件的开头删除“默认”(如下所示):

#The following line must not be removed.
Default
SSID1=MegaBoot_112D36
WebInit=1

...then ConfObj will refuse to read it (I'm assuming it's a key/value issue). ...然后ConfObj将拒绝阅读它(我假设这是一个关键/值问题)。

I haven't actually tested one of these devices without the "Default" there in the configuration, but I'm inclined to listen to the line telling me not to remove it, and I don't want to brick a device really. 我没有在配置中没有“默认”的情况下测试其中一个设备,但是我倾向于听这条线告诉我不要删除它,而且我不想真正搞定一个设备。

In my beginner-ness, I did some more research and realized that what I could do would be remove default programmatically, and then add it back after I've done my ConfObj work, but I wanted to check in here first. 在我的初学者中,我做了一些研究,并意识到我能做的就是以编程方式删除默认值,然后在我完成ConfObj工作后将其添加回来,但我想先在这里查看。 Plus, I was able to get "Default" out pretty easily: 另外,我能够非常轻松地获得“默认”:

with open ('configtest3.dat', 'r+') as f:
    config = f.readlines()
    f.seek(0)
    for i in config:
        if i != 'Default\n':
            f.write(i)
        f.truncate()

...but am unsure of how to shoehorn it back in there. ......但我不确定如何将它重新塞回那里。

I could be shoehorning this entire thing! 我可能会把这整个事情搞得一团糟!

Please enlighten me. 请赐教。


Problem solved! 问题解决了! Thank you for your feedback Sweater-Baron. 感谢您的反馈毛衣男爵。

Here's my final code, which could probably do with some refactoring, but I'll get to that. 这是我的最终代码,这可能与某些重构有关,但我会做到这一点。 I finally have a fully functioning config generator! 我终于有一个功能齐全的配置生成器!

from configobj import ConfigObj
import csv
import os

config = ConfigObj('configtest.dat', list_values=True, raise_errors=False)

with open('config.csv') as csvfile:
    configcsv = csv.reader(csvfile, dialect='excel')
    office = 'null'
    while (office != 'Wooster'):
        for row in configcsv:
            config.filename = row[0] + '-powerswitch.dat'
            config['Hostname'] = row[0]
            config['Ipaddr'] = row[2]
            config['OutletName1'] = row[3]
            config['Gateway'] = row[4]
            config['DNS'] = 'DNSTEST'
            config['Account1'] = row[6]
            config['Password1'] = 'passwordtest'
            config['TimeServer1'] = '10.116.65.17'
            config['TimeZone'] = '800'
            office = row[0]
            config.write()

with open('config.csv') as csvfile:
    configcsv = csv.reader(csvfile, dialect='excel')
    csvfile.seek(0)
    office = 'null'
    while (office != 'Wooster'):
        for row in configcsv:
            filename = row[0] + '-powerswitch.dat'
            with open(filename, 'r') as cfgFile:
                almostCorrect = cfgFile.read()
            correct = "#The following line must not be removed.\nDefault\n" + almostCorrect
            with open(filename, 'w') as cfgFile:
                cfgFile.write(correct)
            print row[0]
            office = row[0]

I realized one thing I was getting hung up on was the initial deletion of "Default" at all. 我意识到我被挂起的一件事是最初删除“默认”。 Instead, I just deleted that from the base file from which I'm configuring the 90 files. 相反,我只是从我正在配置90个文件的基本文件中删除了它。 I'm not sure why I thought I needed it in there in the first place, if I just want to add it back in the end! 我不知道为什么我认为我首先需要它,如果我只是想把它添加到最后!

Thanks again. 再次感谢。

This is sort of an intellectually lazy solution, but it seems like it would require minimal changes to your existing code: 这是一种智力上懒惰的解决方案,但似乎只需要对现有代码进行最小的更改:

Use your existing code to create a config file without the "Default" line. 使用现有代码创建没有“默认”行的配置文件。 Then read that file back into Python as a string. 然后将该文件作为字符串读回Python。 Then erase everything from the file, add the "Default" line to it, and then write back all the other contents of the file that you just read out of it. 然后从文件中删除所有内容,向其中添加“Default”行,然后回写刚读出的文件的所有其他内容。

The following code will add "Default" to the beginning of a text file (also not great code, just demonstrating what I mean): 下面的代码将“Default”添加到文本文件的开头(也不是很好的代码,只是说明我的意思):

with open("ConfigFilePath", "r") as cfgFile:
    almostCorrect = cfgFile.read()
correct = "Default\n" + almostCorrect
# Overwrite the original file with our new string which has "Default" at the beginning:
with open("ConfigFilePath", "w") as cfgFile:
    cfgFile.write(correct)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM