The PyConfigReader API Reference¶
ConfigReader¶
-
class
pyconfigreader.reader.
ConfigReader
(filename='settings.ini', file_object=None, case_sensitive=False)[source]¶ A simple configuration reader class for performing basic config file operations including reading, setting and searching for values.
It is preferred that the value of
filename
be an absolute path. Iffilename
is not an absolute path, then the configuration (ini) file will be saved at the Current Working directory (the value ofos.getcwd()
).If
file_object
is an open file thenfilename
shall point to it’s pathUsage: >>> from pyconfigreader import ConfigReader >>> config = ConfigReader(filename='config.ini') >>> config.set('version', '2') # Saved to section `main` >>> config.set('Key', 'Value', section='Section') # Creates a section `Section` on-the-fly >>> config.set('name', 'main') >>> name = config.get('name') >>> default_section = config.get_items('main') >>> config.close(save=True) # Save on close >>> # Or explicitly call >>> # config.save() >>> # config.close()
Parameters: - filename (str) – The name of the final config file. Defaults to settings.ini.
- file_object (Union[_io.TextIOWrapper, TextIO, io.StringIO]) – A file-like object opened in mode w+. Defaults to a new StringIO object.
- case_sensitive (bool) – Determines whether keys should retain their alphabetic cases or be converted to lowercase. Defaults to True.
Variables: - filename (str) – Path to the ini file
- sections (OrderedDict) – The sections in the ini file
-
close
(save=False)[source]¶ Close the file-like object
If
save
is True, the contents are written to the file on disk first .Caution
Not closing the object might have it update any other instance created later on.
Parameters: save (bool) – write changes to disk
-
get
(key, section=None, evaluate=True, default=None, default_commit=False)[source]¶ Return the value of the provided key
Returns None if the key does not exist. The section defaults to main if not provided. If the value of
key
does not exist anddefault
is not None, the value ofdefault
is returned. And ifdefault_commit
is True, then the value ofdefault
is written to file on disk immediately.If
evaluate
is True, the returned values are evaluated to Python data types int, float and boolean.Changed in version 0.5.0: Expands shell variables while leaving unknown ones unchanged.
Changed in version 0.4.0: Raises NoOptionError when a non-existent key is fetched.
Parameters: - key (str) – The key name
- section (str) – The name of the section, defaults to main
- evaluate (bool) – Determines whether to evaluate the acquired values into Python literals
- default (str) – The value to return if the key is not found
- default_commit (bool) – Also write the value of default to ini file on disk
Raises: NoOptionError – When the key whose value is being fetched does not exist in the section
Returns: The value that is mapped to the key or None if not found
Return type:
-
get_items
(section)[source]¶ Returns an OrderedDict of items (keys and their values) from a section
The values are evaluated into Python literals, if possible.
Returns None if section is not found.
Parameters: section (str) – The section from which items (key-value pairs) are to be read from Returns: An dictionary of keys and their values Return type: Union[OrderedDict, None]
-
load_env
(environment=None, prefix='', commit=False)[source]¶ Load alphanumeric environment variables into configuration file
Default environment is provided by
os.environ()
.The
prefix
is used to filter keys in the environment which start with the value. This is an adaptive mode toto_env()
which prepends the section to the key before loading it to the environment.Parameters: Returns: nothing
-
load_json
(filename='settings.json', section=None, identifier='@', encoding=None)[source]¶ Load config from JSON file
For instance:
# With ``identifier`` as '@', '@counters': { 'start': { 'name': 'scrollers', 'count': 15 }, 'end': { 'name': 'keepers', 'count': 5 } } # will result in a section [counters] start = {'name': 'scrollers', 'count': 15} end = {'name': 'keepers', 'count': 5}
Parameters: Returns: nothing
-
remove_key
(*args, **kwargs)[source]¶ Same as calling
remove_option()
This is just in case one is used to the key-value term pair
-
remove_option
(key, section=None, commit=False)[source]¶ Remove an option from the configuration file
Parameters: Returns: Nothing
Return type: None
-
remove_section
(section)[source]¶ Remove a section from the configuration file whilst leaving the others intact
Parameters: section (str) – The name of the section to remove Returns: Nothing Return type: None
-
save
()[source]¶ Write to file on disk
Write the contents to a file on the disk.
This does not close the file. You have to explicitly call
close()
to do so.Returns: Nothing Return type: None
-
search
(value, case_sensitive=True, exact_match=False, threshold=0.36)[source]¶ Returns a tuple containing the key, value and section of the best match found, else empty tuple
If
exact_match
is False, checks if there exists a value that matches above the threshold value. In this case,case_sensitive
is ignored.If
exact_match
is True then the value ofcase_sensitive
matters.The
threshold
value should be 0, 1 or any value between 0 and 1. The higher the value the better the accuracy.Changed in version 0.5.0: Returns all the matches found
Parameters: Returns: A tuple of the key, value and section of the results, else None
Return type: Union[tuple, None]
-
set
(key, value, section=None, commit=False)[source]¶ Sets the value of key to the provided value
Section defaults to main if not provided. The section is created if it does not exist.
When
commit
is True, all changes up to the current one are written to disk.Parameters: Return type: None
-
show
(output=True)[source]¶ Prints out all the sections and returns a dictionary of the same
Parameters: output (bool) – Print to std.out a string representation of the file contents, defaults to True Returns: A dictionary mapping of sections, options and values Return type: dict
-
to_env
(environment=None, prepend=True)[source]¶ Export contents to an environment
Exports by default to
os.environ()
.By default, the section and option would be capitalised and joined by an underscore to form the key - as an attempt at avoid collision with (any) environment variables.
Usage: >>> reader = ConfigReader() >>> reader.show(output=False) OrderedDict([('main', OrderedDict([('reader', 'configreader')]))]) >>> reader.to_env() >>> import os >>> os.environ['MAIN_READER'] 'configreader' >>> reader.to_env(prepend=False) >>> os.environ['READER'] 'configreader' >>> reader.close()
Parameters: - environment (os.environ) – An environment to export to
- prepend (bool) – Prepend the section name to the key
Returns: Nothing
Return type: None
-
to_json
(file_object=None)[source]¶ Export config to JSON
If a
file_object
is given, it is exported to it else returned as calledUsage: >>> # Example >>> reader = ConfigReader() >>> with open('config.json', 'w') as f: ... reader.to_json(f) >>> # or >>> from io import StringIO >>> s_io = StringIO() >>> reader.to_json(s_io) >>> reader.close()
Parameters: file_object (io.TextIO) – A file-like object for the JSON content Returns: A string or the dumped JSON contents or nothing if file_object is provided Return type: str or None