Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configparser Integers

I am not sure what I am doing wrong. Previously, 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.

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 Protection

CONFIG.ini:

[config_searchandplay]
#Volume Protection
volume_max = 90
volume_min = 10 
like image 347
Ace NA Avatar asked Nov 11 '15 07:11

Ace NA


People also ask

What is a Configparser?

ConfigParser is a Python class which implements a basic configuration language for Python programs. It provides a structure similar to Microsoft Windows INI files. ConfigParser allows to write Python programs which can be customized by end users easily.

What is Configparser module in Python?

The configparser module from Python's standard library defines functionality for reading and writing configuration files as used by Microsoft Windows OS. Such files usually have . INI extension. The INI file consists of sections, each led by a [section] header.

Is Configparser built in Python?

configparser comes from Python 3 and as such it works well with Unicode. The library is generally cleaned up in terms of internal data storage and reading/writing files.

How do I print a Configparser object?

Just use a StringIO object and the configparser's write method. It looks like the only method for "printing" the contents of a config object is ConfigParser. write which takes a file-like object.


2 Answers

You should use

ConfigParser.getint(section, option)

rather than casting.

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
like image 155
Eli Avatar answered Nov 03 '22 05:11

Eli


The problem of your method is that ConfigParser.get gives you a (unicode) string. So you should convert the values first to number (using int() or 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:

vol_max = configParser.getint('config_searchandplay', 'volume_max')
vol_min = configParser.getint('config_searchandplay', 'volume_min')

Although min works on strings:

>>> 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
like image 32
agold Avatar answered Nov 03 '22 05:11

agold