在编写配置文件时使用 ConfigParser 而不是常规的 python.py 文件有什么好处? [英] What is the benefit of using the ConfigParser instead of a regular python.py file when writing configuration files?

查看:19
本文介绍了在编写配置文件时使用 ConfigParser 而不是常规的 python.py 文件有什么好处?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 ConfigParser 模块编写配置文件有一段时间了.然而,最近有一个想法让我印象深刻;为什么不直接使用纯 Python 呢?以这个示例配置文件为例:

I have been using the ConfigParser module to write configuration files for some time. However, a thought recently struck me; why not just use pure Python instead? Take this example configuration file:

[parameters]
# Host
host = stackoverflow.com
port = 22

要将这些值读入我的代码,我会

To read these values into my code, I do

import ConfigParser
config = ConfigParser.SafeConfigParser()
config.read('host.cfg')

host = config.get('parameters', 'host')
port = config.get('parameters', 'port')

另一方面,如果我有这样的配置文件:

On the other hand, if I had a config file like this:

# Host
host = 'stackoverflow.com'
port = 22

在我的主代码中,我可以这样做:

In my main code, I could do this:

from host_cfg import *

那么我从使用 ConfigParser 模块中获得了什么?每种方法的优缺点是什么?

So what do I gain from using the ConfigParser module? What are the pros and cons of each approach?

推荐答案

那么我从使用 ConfigParser 模块中获得了什么?

So what do I gain from using the ConfigParser module?

与 Windows .ini 文件的兼容性.让一些人开心.

Compatibility with Windows .ini files. Makes some people happy.

每种方法的优缺点是什么?

What are the pros and cons of each approach?

ConfigParser 的语法有限,一些相对简单的东西变得非常做作.查看 logging 示例.

ConfigParser has limited syntax and some relatively simple things get very contrived. Look at logging for examples.

Python 语法更简单,更容易使用.没有安全漏洞,因为当他们可以简单地破解您的源代码时,没有人会浪费时间破解配置文件.事实上,他们可以破解大部分内置的 Python 库.就此而言,他们可以自己编写 Python 解释器.

Python syntax is simpler and much easier to work with. There's no security hole, since no one will waste time hacking a config file when they can simply hack your source code. Indeed, they can hack most of the built-in Python library. For that matter, they could cook the Python interpreter itself.

当您的应用程序源代码中的其他地方存在更容易被利用的漏洞时,没有人会浪费时间破解配置文件.

No one wastes time hacking config files when there are much, much easier exploits elsewhere in your application source code.

这篇关于在编写配置文件时使用 ConfigParser 而不是常规的 python.py 文件有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆