我不确定我做错了什么。以前,代码是这样的:
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 ProtectionCONFIG.ini
[config_searchandplay]
#Volume Protection
volume_max = 90
volume_min = 10 发布于 2015-11-11 21:44:33
你的方法的问题是ConfigParser.get会给你一个(unicode)字符串。因此,您应该首先将值转换为number (使用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发布于 2017-03-05 17:23:55
你应该使用
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发布于 2021-06-15 17:40:58
如果可能的话,我更喜欢将任何字符串转换为数字(注意,您需要非常后面的字符串表示的数字)。这是我在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_cfghttps://stackoverflow.com/questions/33645965
复制相似问题