Configparser 整数

Configparser Integers

我不确定我做错了什么。以前,代码是这样的:

volume = min(60, max(30, volume))

但是,在尝试使用 configparser 之后,我的 Twilio 服务器上一直出现 500 错误。

volume_min = configParser.get('config_searchandplay', 'volume_min')
volume_max = configParser.get('config_searchandplay', 'volume_max')
volume = min(volume_max, max(volume_min, volume)) # Max Volume Spam Protection

CONFIG.ini:

[config_searchandplay]
#Volume Protection
volume_max = 90
volume_min = 10 

你的方法的问题是 ConfigParser.get 给了你一个 (unicode) 字符串。所以你应该首先将值转换为数字(使用 int()float()):

vol_max = int(configParser.get('config_searchandplay', 'volume_max'))
vol_min = int(configParser.get('config_searchandplay', 'volume_min'))
volume = min(vol_max, max(vol_min, volume))

或使用各自的便捷方法:ConfigParser.getint or ConfigParser.getfloat:

vol_max = configParser.getint('config_searchandplay', 'volume_max')
vol_min = configParser.getint('config_searchandplay', 'volume_min')

尽管 min 适用于字符串:

>>> min(u'90',u'10')
u'10'

它不会总是给出您正在寻找的答案,因为它会进行字符串比较。以下是您要避免的情况:

>>> min(u'9',u'10')
u'10'

因此您需要将字符串转换为数字:

>>> min(int(u'9'),(u'90'))
9

你应该使用

ConfigParser.getint(section, option)

而不是铸造。

volume_max = configParser.getint('config_searchandplay', 'volume_max')
volume_min = configParser.getint('config_searchandplay', 'volume_min')
volume = min(volume_max, max(volume_min, volume)) # Max Volume Spam Protection

如果可能的话,我更愿意将任何字符串转换为数字(请注意,您需要非常靠后的字符串表示数字)。这是我来自 here.

的辅助函数
def number(a, just_try=False):
    try:
        # First, we try to convert to integer.
        # (Note, that all integer can be interpreted as float and hex number.)
        return int(a)
    except Exception:
        # The integer convertion has failed because `a` contains others than digits [0-9].
        # Next try float, because the normal form (eg: 1E3 = 1000) can be converted to hex also.
        # But if we need hex we will write 0x1E3 (= 483) starting with 0x
        try:
            return float(a)
        except Exception:
            try:
                return int(a, 16)
            except Exception:
                if just_try:
                    return a
                else:
                    raise

def number_config(config):
    ret_cfg = {}
    for sk, sv in config._sections.items():
        ret_cfg[sk] = {k:number(v, True) for k,v in sv.items()}
    return ret_cfg