[英]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.getint
或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
如果可能的话,我更喜欢将任何字符串转换为数字(注意,您需要非常后面的字符串表示数字)。 这是我的辅助函数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.