【问题标题】:How to insert multi-line value using configparser如何使用 configparser 插入多行值
【发布时间】:2015-11-26 04:54:00
【问题描述】:

我必须修改一个与 .ini 文件结构相似的配置文件。 但问题是配置文件有多行用于单个值。如何修改?

例如这里是我要修改的配置。

[INCLUDES]

# Read common prefixes. If any customizations available -- read them from
# common.local
before = common.conf

[Definition]

_daemon = sshd


failregex = ^%(__prefix_line)s(?:error: PAM: )?[aA]uthentication (?:failure|error) for .* from <HOST>( via \S+)?\s*$
        ^%(__prefix_line)s(?:error: PAM: )?User not known to the underlying authentication module for .* from <HOST>\s*$
        ^%(__prefix_line)sFailed \S+ for .*? from <HOST>(?: port \d*)?(?: ssh\d*)?(: (ruser .*|(\S+ ID \S+ \(serial \d+\) CA )?\S+ %(__md5hex)s(, client user ".*", client host ".*")?))?\s*$
        ^%(__prefix_line)sROOT LOGIN REFUSED.* FROM <HOST>\s*$
        ^%(__prefix_line)s[iI](?:llegal|nvalid) user .* from <HOST>\s*$
        ^%(__prefix_line)sUser .+ from <HOST> not allowed because not listed in AllowUsers\s*$
        ^%(__prefix_line)sUser .+ from <HOST> not allowed because listed in DenyUsers\s*$
        ^%(__prefix_line)sUser .+ from <HOST> not allowed because not in any group\s*$
        ^%(__prefix_line)srefused connect from \S+ \(<HOST>\)\s*$
        ^%(__prefix_line)sReceived disconnect from <HOST>: 3: \S+: Auth fail$
        ^%(__prefix_line)sUser .+ from <HOST> not allowed because a group is listed in DenyGroups\s*$
        ^%(__prefix_line)sUser .+ from <HOST> not allowed because none of user's groups are listed in AllowGroups\s*$

ignoreregex =

如果我在写字符串时使用\n,它会显示为

before = test1 \n test2 \n test3 \n test4

有什么办法可以解决这个问题?甚至可以通过 ConfigParser 实现吗?

【问题讨论】:

  • 你读过the documentation,包括它对this document的引用吗?
  • 是的,我阅读了第一个文档。我正在使用 set() 方法设置值,然后 write() 将其写回文件。但它不是在多行中写入值。它正在按原样写入并在文件中打印“\ n”。我正在使用 safeconfigparser 对象。
  • 读回是否正确?只要可以正确解析,文件在视觉上的外观应该是怎样的。
  • 我还没有测试过。这是一个fail2ban过滤器配置文件。
  • 如果您打算将文件与某些外部源一起使用(即,不使用 Python 自己的 ConfigParser 将其读回),您需要进行一些研究和测试以确保格式兼容。有许多程序可以读取和写入看起来相似但在各种边缘情况下不同的配置文件(例如您要询问的那个)。 ConfigParser 只是一种变体,不能保证它可以与任何其他类似格式正确互操作。

标签: python configparser


【解决方案1】:

解决方法:

您可以这样做的一种方法是将每一行添加到一个新选项中。喜欢:

[SECTION]
failregex = ...
replace 1 = ...
replace 2 = ...

之后,您只需将 ini 文件作为文本文件打开并找到每个替换选项并将“replace 1 =”替换为空格。根据这篇文章,缩进足以让 configparser 将其作为多行值处理: New lines with ConfigParser?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-30
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    相关资源
    最近更新 更多