【问题标题】:Is there a way to read/write config files without section headers in python? [duplicate]有没有办法在 python 中读取/写入没有节标题的配置文件? [复制]
【发布时间】:2018-05-09 09:07:31
【问题描述】:

我想使用 python 修改一个 hostapd 配置文件

#
# Wireless Interface
#
interface=wlp2s0
driver=nl80211
#
# Wireless Environment
#
# Currently not working due to
# regulatory restrictions on 5GHz wifi
# in driver
#
ssid=bobthebuilder
hw_mode=a
ieee80211d=1
country_code=GB
channel=40
ieee80211n=1

(等)

但是 configparser 库需要配置部分的标头才能使用 - 我们还有另一个库可以用来编辑此文件吗?

【问题讨论】:

  • 该答案中的 ConfigObj 库看起来可以满足我的需求

标签: python


【解决方案1】:

似乎是一个非常简单的配置文件语法。为什么不编写自己的配置解析器?

conf = {}
with open('config.cfg') as fp:
  for line in fp:
    if line.startswith('#'):
      continue
    key, val = line.strip().split('=')
    conf[key] = val

【讨论】:

  • .split('=', 1) 稍微好一点,以防值中包含 =
  • 是的。这只是一个非常简单的例子。对于生产用途,您可能还需要一些语法验证。但我也强烈建议使用一些标准配置格式。配置文件的典型选择是 ini 格式(configparser 期望的)、yaml 或 json。
猜你喜欢
  • 2020-05-21
  • 2019-02-11
  • 2020-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多