如何使用 Python 编辑带有制表符和大括号的复杂配置文件?
How do I edit a complex config file with tabs and curly brackets using Python?
我有一个如下所示的配置文件:
# EAP types NOT listed here may be supported via the "eap2" module.
# See experimental.conf for documentation.
#
eap {
# Invoke the default supported EAP type when
# EAP-Identity response is received.
#
# The incoming EAP messages DO NOT specify which EAP
# type they will be using, so it MUST be set here.
#
# For now, only one default EAP type may be used at a time.
#
# If the EAP-Type attribute is set by another module,
# then that EAP type takes precedence over the
# default type configured here.
#
default_eap_type = peap
# A list is maintained to correlate EAP-Response
# packets with EAP-Request packets. After a
# configurable length of time, entries in the list
# expire, and are deleted.
#
我希望能够编辑eap结构下default_eap_type选项的值。我不能简单地做一个子字符串,因为 default_eap_type 再次出现在配置文件的另一个位置,但在不同的结构下。使用 Python 更改值的最佳方法是什么?
如果您没有以下格式的解析器,则类似这样:
output_lines = []
is_eap = False
for line in file:
if line.strip().startswith('eap {'):
is_eap = True
elif line.strip().split()[1] == '{':
is_eap = False
if is_eap:
output_lines.append(process_line(line))
else:
output_lines.append(line)
这非常粗糙,但希望对您有所帮助。
我有一个如下所示的配置文件:
# EAP types NOT listed here may be supported via the "eap2" module.
# See experimental.conf for documentation.
#
eap {
# Invoke the default supported EAP type when
# EAP-Identity response is received.
#
# The incoming EAP messages DO NOT specify which EAP
# type they will be using, so it MUST be set here.
#
# For now, only one default EAP type may be used at a time.
#
# If the EAP-Type attribute is set by another module,
# then that EAP type takes precedence over the
# default type configured here.
#
default_eap_type = peap
# A list is maintained to correlate EAP-Response
# packets with EAP-Request packets. After a
# configurable length of time, entries in the list
# expire, and are deleted.
#
我希望能够编辑eap结构下default_eap_type选项的值。我不能简单地做一个子字符串,因为 default_eap_type 再次出现在配置文件的另一个位置,但在不同的结构下。使用 Python 更改值的最佳方法是什么?
如果您没有以下格式的解析器,则类似这样:
output_lines = []
is_eap = False
for line in file:
if line.strip().startswith('eap {'):
is_eap = True
elif line.strip().split()[1] == '{':
is_eap = False
if is_eap:
output_lines.append(process_line(line))
else:
output_lines.append(line)
这非常粗糙,但希望对您有所帮助。