Configparser整数

Ace*_* NA 3 python parsing config configparser

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

volume = min(60, max(30, volume))
Run Code Online (Sandbox Code Playgroud)

但是在尝试使用configparser之后,我的Twilio Server上出现了500错误.

volume = min(configParser.get('config_searchandplay', 'volume_max'), max(configParser.get('config_searchandplay', 'volume_min'), volume)) #Max Volume Spam Protection
Run Code Online (Sandbox Code Playgroud)

CONFIG.INI

[config_searchandplay]
#Volume Protection
volume_max = 90
volume_min = 10 
Run Code Online (Sandbox Code Playgroud)

Eli*_*Eli 12

你应该使用:

ConfigParser.getint(section, option)
Run Code Online (Sandbox Code Playgroud)

而不是铸造.

volume = min(configParser.getint('config_searchandplay', 'volume_max'), max(configParser.getint('config_searchandplay', 'volume_min'), volume)) #Max Volume Spam Protection
Run Code Online (Sandbox Code Playgroud)


ago*_*old 8

你的方法的问题是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))
Run Code Online (Sandbox Code Playgroud)

或使用各自的方便方法:ConfigParser.getintConfigParser.getfloat

vol_max = configParser.getint('config_searchandplay', 'volume_max')
vol_min = configParser.getint('config_searchandplay', 'volume_min')
Run Code Online (Sandbox Code Playgroud)

虽然min适用于字符串:

>>> min(u'90',u'10')
u'10'
Run Code Online (Sandbox Code Playgroud)

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

>>> min(u'9',u'10')
u'10'
Run Code Online (Sandbox Code Playgroud)

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

>>> min(int(u'9'),(u'90'))
9
Run Code Online (Sandbox Code Playgroud)