【问题标题】:Configparser set with no section没有节的 Configparser 集
【发布时间】:2013-07-19 13:42:39
【问题描述】:

有没有办法让 python 中的 configparser 设置一个值而不在配置文件中包含部分?

如果没有,请告诉我任何替代方案。

谢谢。

更多信息: 所以基本上我有一个格式为: Name: value 这是一个系统文件,我想更改给定名称的值。我想知道这是否可以通过模块轻松完成,而不是手动编写解析器。

【问题讨论】:

  • ConfigParser 主要用于从文件中读取设置,但听起来您想添加或更改其中的内容,对吗?这比让它读取没有任何部分的文件更难......

标签: python python-2.7 configparser


【解决方案1】:

您可以使用csv 模块来完成大部分工作来解析文件并在您进行更改后将其写回——所以它应该相对容易使用。我从其中一个answers 中得到了这个想法,并提出了一个名为Using ConfigParser to read a file without section name 的类似问题。

但是我已经对其进行了许多更改,包括对其进行编码以在 Python 2 和 3 中工作,取消对它使用的键/值分隔符进行硬编码,使其几乎可以是任何东西(但默认情况下是冒号),以及一些优化。

from __future__ import print_function  # For main() test function.
import csv
import sys
PY3 = sys.version_info.major > 2


def read_properties(filename, delimiter=':'):
    """ Reads a given properties file with each line in the format:
        key<delimiter>value. The default delimiter is ':'.

        Returns a dictionary containing the pairs.

            filename -- the name of the file to be read
    """
    open_kwargs = dict(mode='r', newline='') if PY3 else dict(mode='rb')

    with open(filename, **open_kwargs) as csvfile:
        reader = csv.reader(csvfile, delimiter=delimiter, escapechar='\\',
                            quoting=csv.QUOTE_NONE)
        return {row[0]: row[1] for row in reader}


def write_properties(filename, dictionary, delimiter=':'):
    """ Writes the provided dictionary in key-sorted order to a properties
        file with each line of the format: key<delimiter>value
        The default delimiter is ':'.

            filename -- the name of the file to be written
            dictionary -- a dictionary containing the key/value pairs.
    """
    open_kwargs = dict(mode='w', newline='') if PY3 else dict(mode='wb')

    with open(filename, **open_kwargs) as csvfile:
        writer = csv.writer(csvfile, delimiter=delimiter, escapechar='\\',
                            quoting=csv.QUOTE_NONE)
        writer.writerows(sorted(dictionary.items()))


def main():
    data = {
        'Answer': '6*7 = 42',
        'Knights': 'Ni!',
        'Spam': 'Eggs',
    }

    filename = 'test.properties'
    write_properties(filename, data)  # Create csv from data dictionary.

    newdata = read_properties(filename)  # Read it back into a new dictionary.
    print('Properties read: ')
    print(newdata)
    print()

    # Show the actual contents of file.
    with open(filename, 'rb') as propfile:
        contents = propfile.read().decode()
    print('File contains: (%d bytes)' % len(contents))
    print('contents:', repr(contents))
    print()

    # Tests whether data is being preserved.
    print(['Failure!', 'Success!'][data == newdata])

if __name__ == '__main__':
     main()

【讨论】:

  • 更改 PY3=sys.version_info[0] &gt; 2 使其与 Python 2.6.6、Python 3.4.1 和 Jython 2.7b2 兼容。在该版本的 Jython 中,sys.version_info 返回一个元组。感谢您的代码。
  • @martineau:这个解决方案真的很有帮助。我可以读取我可以写入和附加的数据。如果您可以提供编辑配置文件的解决方案,那将非常有帮助。例如场景是,假设我通过每次使用您的方法附加一些用户到 sshd_config 文件。现在我想删除一个用户及其相应的设置,那么我应该使用什么方法。请帮忙。如果您没有收到我的问题,也请告诉我。谢谢。
  • @AbhishekVerma:这个答案中的函数被传递并以字典格式返回数据,所以看起来你应该能够通过修改字典来做你想做的事情——尽管我不熟悉 sshd_config 文件格式。无论如何,如果您不知道该怎么做,我建议您发布一个新问题。
【解决方案2】:

我不知道 configparser 无法做到这一点,它非常面向部分。

另一种方法是使用由 Michael Foord 命名为 ConfigObjVoidspace Python 模块。在他写的一篇题为An Introduction to ConfigObj 的文章的The Advantages of ConfigObj 部分中,它说:

ConfigObj 的最大优点是简单。即使是微不足道的 配置文件,你只需要几个键值对, ConfigParser 要求它们位于“部分”内。 ConfigObj 没有 有这个限制,并且已经将配置文件读入内存, 访问成员非常简单。

强调我的。

【讨论】:

  • 感谢马蒂诺的信息。你知道默认情况下 Python 中是否已经有替代模块吗?
【解决方案3】:

我个人喜欢将我的配置文件作为 XML。一个示例(取自 ConfigObj 文章以进行比较)您可以创建一个名为 config.xml 的文件,其内容如下:

<?xml version="1.0"?>
<config>
  <name>Michael Foord</name>
  <dob>12th August 1974</dob>
  <nationality>English</nationality>
</config>

在 Python 中,您可以通过以下方式获取值:

>>> import xml.etree.cElementTree as etree
>>> config = etree.parse("config.xml")
>>> config.find("name").text
'Michael Foord'
>>> config.find("name").text = "Jim Beam"
>>> config.write("config.xml")

现在,如果我们查看 config.xml,我们会看到:

<config>
  <name>Jim Beam</name>
  <dob>12th August 1974</dob>
  <nationality>English</nationality>
</config>

优点与通用 XML 相同 - 它是人类可读的,在您能想象到的几乎所有编程语言中已经存在许多体面的解析器,并且它支持分组和属性。作为额外的好处,当您的配置文件变大时,您还可以合并 XML 验证(使用模式)以在运行前发现错误。

【讨论】:

  • 其实我没有这个能力。我已经有一个 .conf 文件,其中的值采用“名称:值”之类的格式,我尝试修改它们。
  • @Haros:你用什么来读取你已有的 .config 文件?
  • @Haros 对其他方法的任何限制都应添加到问题中。
猜你喜欢
  • 2011-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2017-07-26
  • 2017-07-02
  • 2023-01-08
  • 2017-01-25
相关资源
最近更新 更多