Package: configpilot
ConfigPilot is a lightweight and powerful configuration parser for Python that automates checks and typecasting.Do everything you did in fewer lines of code!FeaturesSimple and concise syntax.Lightweight and fast.Automatic type casting.Automation of value checks.Support for primitive Python types and user-defined types.Support for multi-line values and lists.No dependency.InstallationThe recommended way to install ConfigPilot is to usepip3:$pip3installconfigpilotConfigPilot requires Python 3.6 or later.Import ConfigPilot into your project:fromconfigpilotimportConfigPilot,OptionSpec# Exceptions (optional)fromconfigpilotimportConfigPilotError,NoSectionError,\NoOptionError,IllegalValueErrorExamples1. A simple exampleConfiguration file# This is a comment[author]name='John DOE'# This is an inline commentage=27github='https://github.com'skills='sleep well on airplanes''have a terrific family recipe for brownies''always up for dessert'Quotes are optional for strings (unless you put special characters).For this first example, we want to retrieve:Thenameas a string.Theageas an integer between0and100.Thegithuboption as a string.Theskillsas a list of strings.To achieve this, we have to:Define the desired file structure.Instantiate aConfigPilotobject and indicate the structure of the file.Read the file and check that it does not contain any errors in terms of format or content.Retrieve values.Python codeoptions=[OptionSpec(section='author',option='name'),OptionSpec(section='author',option='age',allowed=range(0,100),type=int),OptionSpec(section='author',option='github'),OptionSpec(section='author',option='skills',type=[str])]config=ConfigPilot()config.register(*options)config.read('/path/file.conf')ifnotconfig.is_opened:print('Error: unable to read the configuration file.')exit(1)ifconfig.errors:print('Error: some options are incorrect.')exit(1)name=config.author.name# 'John DOE'age=config.author.age# 27github=config.author.github# 'https://github.com'skills=config.author.skills# ['sleep well on airplanes',#  'have a terrific family recipe for brownies',#  'always up for dessert']# Alternative syntaxname=config['author']['name']age=config['author']['age']github=config['author']['github']skills=config['author']['skills']2. Use more complex typesConfiguration file[general]mode:masterinterface:ens33port:5000initDelay:0.5[logging]enabled:false[nodes]slaves:10.0.0.110.0.0.210.0.0.3What we want to retrieve:Themodeoption as a string. Two values will be possible:masterorslave.Theinterfaceas a string. If the option is not specified, we will use the default valueens33.Theportas an integer between1024and49151. The default value will be4000.TheinitDelayoption as a float. The default value will be0.0.Theenabledoption, from theloggingsection, as a boolean.Theslaves, from thenodessection, as a list ofIPv4Address(from theipaddressmodule).Python codefromipaddressimportIPv4Addressoptions=[OptionSpec(section='general',option='mode',allowed=('master','slave')),OptionSpec(section='general',option='interface',default='ens33'),OptionSpec(section='general',option='port',allowed=range(1024,49151),default=4000,type=int),OptionSpec(section='general',option='initDelay',default=0.0,type=float),OptionSpec(section='logging',option='enabled',type=bool),OptionSpec(section='nodes',option='slaves',type=[IPv4Address])]config=ConfigPilot()config.register(*options)config.read('/path/file.conf')ifnotconfig.is_opened:print('Error: unable to read the configuration file.')exit(1)ifconfig.errors:print('Error: some options are incorrect.')exit(1)mode=config.general.mode# 'master'interface=config.general.interface# 'ens33'port=config.general.port# 5000init_delay=config.general.initDelay# 0.5logs_enabled=config.logging.enabled# Falseslaves=config.nodes.slaves# [IPv4Address('10.0.0.1'),#  IPv4Address('10.0.0.2'),#  IPv4Address('10.0.0.3')]3. Use functions and lambda functionsConfiguration file[boot]hexCode:0x2A[statistics]lastBoot:2020-02-01 10:27:00lastCrash:2019-12-10 09:00:00What we want to retrieve:ThehexCodeoption as an integer (base 16).ThelastBootoption as adatetimeobject.ThelastCrashoption as adatetimeobject.We cannot set thetypeparameter of theOptionSpecobjects todatetimebecause the constructor ofdatetimeexpects several parameters. The values contained in the configuration file are strings with a specific format. So, we have to process these data with a dedicated function.Python codefromdatetimeimportdatetimedefstring_to_datetime(value):'''Cast a string to a datetime object.'''# Do not handle any exceptions that can be raised in this function.# They are processed by ConfigPilot: the option, which called the# function, is considered wrong if an exception is thrown.returndatetime.strptime(value,'%Y-%m-%d%H:%M:%S')options=[OptionSpec(section='boot',option='hexCode',type=lambdax:int(x,16)),OptionSpec(section='statistics',option='lastBoot',type=string_to_datetime),OptionSpec(section='statistics',option='lastCrash',type=string_to_datetime)]config=ConfigPilot()config.register(*options)config.read('/path/file.conf')ifnotconfig.is_opened:print('Error: unable to read the configuration file.')exit(1)ifconfig.errors:print('Error: some options are incorrect.')exit(1)boot_hex_code=config.boot.hexCode# 42last_boot=config.statistics.lastBoot# datetime.datetime(2020, 2, 1, 10, 27)last_crash=config.statistics.lastCrash# datetime.datetime(2019, 12, 10, 9, 0)ClassesOptionSpecA user-created object that represents the constraints that an option must meet to be considered valid.DefinitionOptionSpec(section,option,allowed=None,default=None,type=str)Parameters / GetterssectionThe name of a section in the file.Type:stroptionThe name of an option in the specified section.Type:strallowedThe list or range of allowed values.Type:object that supports the 'in' operator (membership)Default:NonedefaultThe default value of the option if it does not exist.Must be an object of the same type as the value obtained after the cast (see thetypeparameter).Type:objectDefault:NonetypeThe expected value type for this option.Set it toint,float,bool,str(default) or any other type of object.If you expect a list of values, use instead[int],[float],[bool],[str](equivalent oflist) or even[MyClass].Type:typeorlistDefault:strConfigPilotDefinitionConfigPilot()Methodsregister(*specifications)Register one or several specifications. You can call this method multiple times.Each option in the configuration file must have its own specification. Call thereadmethod next.*specificationsparameter: one or severalOptionSpec.read(filename, encoding='utf-8')Read and parse a configuration file according to the registered specifications.filenameparameter: the name of the configuration file to read.encodingparameter: the name of the encoding used to decode the file. The default encoding isUTF-8.GettersfilenameThe name of the last opened file.Type:stris_openedReturn a boolean that indicates whether the file is opened or not.Type:boolerrorsReturn a dictionary containing sections and options that do not meet the specifications.Type:dictContributingComments and enhancements are welcome.All development is done onGitHub. UseIssuesto report problems and submit feature requests. Please include a minimal example that reproduces the bug.DonateConfigPilot is completely free and open source. It has been fully developed on my free time. If you enjoy it, please consider donating to support the development.🎉 Donate via PayPalLicenseCopyright 2017-2020 Valentin BELYN.Code released under the MIT license. See theLICENSEfor details.