Python中处理配置文件的用户友好方法?

2 投票
4 回答
1350 浏览
提问于 2025-04-16 17:31

我想写一个程序,当发生某个事件时,它能给一个或多个指定的收件人发送电子邮件。为此,我需要用户在一个配置文件里写入邮件服务器的参数。可能的参数包括:服务器地址、端口、是否使用SSL(真/假),还有一个想要发送邮件的收件人列表。

那么,什么样的方式对用户来说最友好、最符合最佳实践呢?

当然,我可以用一个Python文件,把正确的参数写进去,然后让用户自己填写,但我觉得这样不够友好。我还听说过Python里的'config'模块,但我觉得这个模块是用来自己创建配置文件的,而不是让用户自己填写的。

4 个回答

1

这种解决方案有什么缺点:

ch = 'serveradress = %s\nport = %s\nssl = %s'

a = raw_input("Enter the server's address : ")

b = 'a'
bla = "\nEnter the port : "
while not all(x.isdigit() for x in b):
    b = raw_input(bla)
    bla = "Take care: you must enter digits exclusively\n"\
          +"  Re-enter the port (digits only) : "

c = ''
bla = "\nChoose the ssl option (t or f) : "
while c not in ('t','f'):
    c = raw_input(bla)
    bla = "Take care: you must type f or t exclusively\n"\
          +"  Re-choose the ssl option : "


with open('configfile.txt','w') as f:
    f.write(ch % (a,b,c))

.

附言

我在jonesy的帖子中看到,配置文件中的值可能需要加引号。如果是这样,并且你希望用户不需要自己手动加引号,你只需添加

a = a.join('""')
b = b.join('""')
c = c.join('""')

.

编辑

ch = 'serveradress = %s\nport = %s\nssl = %s'

d = {0:('',
        "Enter the server's address : "),
     1:("Take care: you must enter digits exclusively",
        "Enter the port : "),
     2:("Take care: you must type f or t exclusively",
        "Choose the ssl option (t or f) : ")  }

def func(i,x):
    if x is None:
        return False
    if i==0:
        return True
    elif i==1:
        try:
            ess = int(x)
            return True
        except:
            return False
    elif i==2:
        if x in ('t','f'):
            return True
        else:
            return False


li = len(d)*[None]
L = range(len(d))

while True:

    for n in sorted(L):
        bla = d[n][1]
        val = None
        while not func(n,val):
            val = raw_input(bla)
            bla = '\n  '.join(d[n])
        li[n] = val.join('""')

    decision = ''
    disp = "\n====== If you choose to process, =============="\
           +"\n    the content of the file will be :\n\n" \
           + ch % tuple(li) \
           + "\n==============================================="\
           + "\n\nDo you want to process (type y) or to correct (type c) : "
    while decision not in ('y','c'):
        decision = raw_input(disp)
        disp = "Do you want to process (type y) or to correct (type c) ? : "

    if decision=='y':
        break
    else:
        diag = False
        while not diag:
            vi = '\nWhat lines do you want to correct ?\n'\
                 +'\n'.join(str(j)+' - '+line for j,line in enumerate((ch % tuple(li)).splitlines()))\
                 +'\nType numbers of lines belonging to range(0,'+str(len(d))+') separated by spaces) :\n'
            to_modify = raw_input(vi)
            try:
                diag = all(int(entry) in xrange(len(d)) for entry in to_modify.split())
                L = [int(entry) for entry in to_modify.split()]
            except:
                diag = False


with open('configfile.txt','w') as f:
    f.write(ch % tuple(li))

print '-*-  Recording of the config file : done  -*-'
2

无论你的用户技术水平有多高,他们在编辑文本文件时总会出错。比如,他们可能会把文件保存在错误的地方,或者用MS Word来编辑文本文件,甚至可能会打错字。为了避免这些问题,我建议你做一个图形界面(gui),可以检查用户输入的内容,并把配置文件放在正确的格式和位置上。用Tkinter做一个简单的图形界面,应该能满足你的需求。

4

你是在说配置文件需要是有效的Python代码,这让它不太友好吗?我觉得在文件里写一些像这样的内容:

 server = 'mail.domain.com'
 port = 25

...等等,其实还是挺直观的,而且也符合Python的语法。如果你不想让用户知道他们需要给字符串加引号,那你可以考虑用YAML格式。我几乎只用YAML来写配置文件,觉得它非常直观,我认为对普通用户来说也很容易理解(不过这需要一个第三方模块 - PyYAML):

 server: mail.domain.com
 port: 25

用pyyaml来加载配置文件很简单:

>>> import yaml
>>> yaml.load("""a: 1
... b: foo
... """)
{'a': 1, 'b': 'foo'}

用文件也很方便。

>>> with open('myconfig.yaml', 'r') as cfile:
...    config = yaml.load(cfile)
... 

现在config里包含了所有的参数。

撰写回答