[英]Configparser Integers
I am not sure what I am doing wrong.我不确定我做错了什么。 Previous the code was this:
以前的代码是这样的:
volume = min(60, max(30, volume))
However after trying with configparser I keep getting a 500 error on my Twilio Server.但是,在尝试使用 configparser 后,我的 Twilio 服务器上不断出现 500 错误。
volume = min(configParser.get('config_searchandplay', 'volume_max'), max(configParser.get('config_searchandplay', 'volume_min'), volume)) #Max Volume Spam Protection
CONFIG.ini配置文件
[config_searchandplay]
#Volume Protection
volume_max = 90
volume_min = 10
You should use:你应该使用:
ConfigParser.getint(section, option)
Rather then casting.而不是铸造。
volume = min(configParser.getint('config_searchandplay', 'volume_max'), max(configParser.getint('config_searchandplay', 'volume_min'), volume)) #Max Volume Spam Protection
The problem of your method is that ConfigParser.get
gives you a (unicode) string.你的方法的问题是
ConfigParser.get
给你一个(unicode)字符串。 So you should convert the values first to number (using int()
or float()
):因此,您应该首先将值转换为数字(使用
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))
Or use the respective convenience methods: ConfigParser.getint
or ConfigParser.getfloat
:或者使用各自的便捷方法:
ConfigParser.getint
或ConfigParser.getfloat
:
vol_max = configParser.getint('config_searchandplay', 'volume_max')
vol_min = configParser.getint('config_searchandplay', 'volume_min')
Although min
works on strings:虽然
min
适用于字符串:
>>> min(u'90',u'10')
u'10'
It will not always give the answer you are looking for since it does a string comparison.它不会总是给出您正在寻找的答案,因为它会进行字符串比较。 The following is what you want to avoid:
以下是您要避免的情况:
>>> min(u'9',u'10')
u'10'
Therefore you need to convert the string to a number:因此,您需要将字符串转换为数字:
>>> min(int(u'9'),(u'90'))
9
I prefer to convert any string to a number if it is possible (Note, you need very rear a string represented number).如果可能的话,我更喜欢将任何字符串转换为数字(注意,您需要非常后面的字符串表示数字)。 Here is my helper function from here .
这是我的辅助函数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.