- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
下面是我的示例配置文件
[HEAD1]
key1 = val1
key2 = val2
[HEAD2]
key1 =
key2 = val2
我想编写一个高效的代码,该代码会向用户抛出错误,指示是否有任何选项缺少值(如果为空,则“=”后没有给定值)
我正在使用 Python ConfigParser 模块
import ConfigParser
config = ConfigParser.RawConfigParser()
config.read("./mytest.cfg")
for section in config.sections():
for option in config.options(section):
if not config.get(section, option):
print "Option: %s has no value under section %s" %(option,section)
我很高兴知道是否有任何有效的方法可以快速识别相同的内容,而不是使用 2 个循环进行迭代。
最佳答案
从解析器的角度来看,HEAD2
部分中的选项 key1
确实 有一个值;一个空字符串实例,它构成解析器的有效值:
print repr(config.get('HEAD2', 'key1'))
# Output: ''
您可以子类 RawConfigParser
并覆盖 _read()
方法,以在将这些空字符串值插入内部字典之前捕获它们。但是,_read
相当冗长,并且捕获其中不需要的值显得有点笨拙。如果我的 Python 版本低于 2.6,我只会走这条路。
在这种情况下,您可以在处理选项行时添加对空字符串的检查
if optval == '':
print "Option: %s has no value under section %s" % (optname, cursect['__name__'])
empty values have been handled之后.
<小时/>从 Python 2.6 开始,RawConfigParser
(及其后代)采用可选参数 dict_type
,它允许您传入解析器将在内部使用的自定义字典类。
从 Python 2.7 开始,默认值为 collections.OrderedDict
,并回退到内置 dict
。
您可以创建一个自定义dict
类来警告空字符串实例作为值:
# as done in ConfigParser
try:
from collections import OrderedDict as _default_dict
except ImportError:
# fallback for setup.py which hasn't yet built _collections
_default_dict = dict
class NotifyEmptyStringValueDict(_default_dict):
def __setitem__(self, key, value):
if value == "":
# Consider raising an exception here instead, e.g. ValueError,
# unless you don't want empty string values to break the parsing
# and just want a warning message to be displayed while parsing continues
print "Option: %s has no value under section %s" % (key, self['__name__'])
# accessing self['__name__'] obviously raises a KeyError when used
# outside the context of a parser instance. In a parser, this holds
# the section name
_default_dict.__setitem__(self, key, value)
然后使用此类作为 dict_type
实例化您的解析器:
config = ConfigParser.RawConfigParser(dict_type=NotifyEmptyStringValueDict)
config.read("./mytest.cfg")
两个选项,在 Python < 2.6 中覆盖 RawConfigParser
子类中的 _read
并在 Python 中使用自定义可变映射类型作为 dict_type
> = 2.6,优点是在解析配置时已经执行了检查;无需再次迭代完全解析的配置。
关于Python ConfigParser 检查选项是否为空的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54901114/
我正在创建每日报价服务器。我正在阅读 INI 文件中的选项,其文本如下: [Server] host = port = 17 [Quotes] file=quotes.txt 但是,当我使用 Conf
我在从 ini 文件的 [.ShellClassInfo] 部分读取变量时遇到问题。 我的ini文件:(上面和下面有一个空的中断) [.ShellClassInfo] IconResource=\\s
如何重命名 ConfigParser 对象中的部分? 最佳答案 示例辅助函数 - 确实很傻,但它可能会节省一些人几分钟的工作...... def rename_section(cp, section_
我正在使用 Python configparser 从 ini 文件中读取配置。 95% 的情况下,它运行良好。如果不对 ini 文件进行任何更改(例如,在回归测试的中间),configparser
我想做的(理想情况下)是将 with 与字典一起使用来一次设置整个参数部分。经过一些实验,我想出了以下代码,它引发了 AttributeError: import configparser impor
下面是我的示例配置文件 [HEAD1] key1 = val1 key2 = val2 [HEAD2] key1 = key2 = val2 我想编写一个高效的代码,该代码会向用户抛出错误,指示是否有
我只是想知道。是否有机会在 *.ini 文件中创建部分来仅存储没有键的值?我要在本地主机和其他服务器中存储已用端口的列表,我的列表如下所示: [servers] localhost:1111 loca
我正在看Python 3.6 documentation它说的地方 By default, section names are case sensitive but keys are not [1].
How do I put a semicolon in a value in python configparser? python - 2.7 我有一个 python 配置解析器,其中有一个部分,其
我正在使用 Python 的老式 configparser模块从文件系统读取配置文件。 为了检查用户提供的配置文件是否使用正确的“语法”,我将所有部分键和子键与引用配置文件 ref_config.in
我有一个名为 foo.cfg 的模板文件: [Box] box.active={box_activate} resolution_tracker.active=true box.api_key={bo
ConfigParser 也读取注释。为什么?这不应该是“忽略”内联评论的默认设置吗? 我使用以下脚本重现我的问题: import configparser config = configparser
基于 ConfigParser 模块,我如何过滤并抛出 ini 文件中的所有注释? import ConfigParser config = ConfigParser.ConfigParser() c
我正在使用 Python 2.6 编写名为 config.ini 的 .ini 文件。这是我的代码: def saveConfig(self, selection, value, bool):
场景: 我有一个配置文件,用于维护要执行的自动化测试的列表。这些测试是长期循环执行的。 配置文件的设计方式使得 ConfigParser 可以读取它。由于有两个三个参数,我需要通过每个测试。 现在,此
我正在编写一个脚本,该脚本扫描不同目录中的一系列配置文件以确保它们具有特定值:在这种情况下,它们必须具有 MySection 部分,该部分必须有选项Opt1,它不能等于0。如果它通过了所有这些测试,文
我尝试使用 configparser 模块,但我遇到了一点问题。 这是一个代码示例: import configparser ini_file = """[s1]\nl1 = 01\n= = 02\n
如何使用 python 配置解析器获取单个部分下的每个条目并写入新文件而不实际指定每个条目 例如,我如何在不使用 config.get 并列出每个条目的情况下获取“测试”部分下的所有内容并写入新文件?
使用 ConfigParser 我可以轻松读取键的值,如下例所示 - #config.cfg [NODE] 192.168.31.22 = node22 192.168.31.23 = node23
我正在尝试制作一款游戏,玩家每次玩游戏时都会从 ini 文件中的值中扣除 0.5。但是我不断收到错误,我不知道该怎么做。这是我的代码。不要担心评论,这些是给我的,我稍后会关闭 while 循环。这只是
我是一名优秀的程序员,十分优秀!