python - 使用python处理配置文件的用户友好方式吗?

原文 标签 python configuration

Userfriendly way of handling config files in python?

I want to write a program that sends an e-mail to one or more specified recipients when a certain event occurs. For this I need the user to write the parameters for the mail server into a config. Possible values are for example: serveradress, ports, ssl(true/false) and a list of desired recipients.

Whats the user-friendliest/best-practice way to do this?

I could of course use a python file with the correct parameters and the user has to fill it out, but I wouldn't consider this user friendly. I also read about the 'config' module in python, but it seems to me that it's made for creating config files on its own, and not to have users fill the files out themselves.

Answer

Are you saying that the fact that the config file would need to be valid Python makes it unfriendly? It seems like having lines in a file like:

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

...etc would be intuitive enough while still being valid Python. If you don't want the user to have to know that they have to quote strings, though, you might go the YAML route. I use YAML pretty much exclusively for config files and find it very intuitive, and it would also be intuitive for an end user I think (though it requires a third-party module - PyYAML):

 server: mail.domain.com
 port: 25

Having pyyaml load it is simple:

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

With a file it's easy too.

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

config now contains all of the parameters.

翻译

我想编写一个程序,当某个事件发生时,该程序将电子邮件发送给一个或多个指定的收件人。为此,我需要用户将邮件服务器的参数写入配置中。可能的值例如:serveradress,端口,ssl(true / false)和所需收件人的列表。

什么是用户最友好/最佳实践的方式?

我当然可以使用带有正确参数的python文件,并且用户必须填写该文件,但我认为此用户友好。我还阅读了有关python中的'config'模块的信息,但在我看来,它是用于自行创建配置文件,而不是让用户自己填写文件的。
最佳答案
您是在说配置文件需要有效的Python的事实使其变得不友好吗?似乎在文件中包含以下行:

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


... etc足够直观,而仍然是有效的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现在包含所有参数。
相关推荐

python - PyOpenGL:渲染...好吧...真正的一切

python - 学习python并遇到第一个程序的麻烦

python - 导入GDK时出现问题

javascript - 如何像Javascript一样调用Python函数

python - python tarinfo权限位

python - Django syncdb错误

python - Python总和麻烦

python - 如果要构建自定义数据库,该怎么办? [关闭]

python - 对象继承和嵌套cmd

python - 运行由字符串定义的类的特定方法