簡體   English   中英

配置解析器整數

[英]Configparser Integers

我不確定我做錯了什么。 以前的代碼是這樣的:

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

但是,在嘗試使用 configparser 后,我的 Twilio 服務器上不斷出現 500 錯誤。

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

配置文件

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

你應該使用:

ConfigParser.getint(section, option)

而不是鑄造。

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

你的方法的問題是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.getintConfigParser.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

如果可能的話,我更喜歡將任何字符串轉換為數字(注意,您需要非常后面的字符串表示數字)。 這是我的輔助函數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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM