Search code examples
pythonvariablesconfiguration-filesconfigparser

ConfigParser: Check If variable in Config File exists


I am currently trying to check if my config file has a variable in it. In the documentation I only saw a check for the sections but not a variable inside the section.

Current code:

#!/usr/bin/python3
from configparser import ConfigParser

def ImportConfig(arg):
    config_file = ConfigParser()
    config_file.read("configFile")
    config = config_file[""+arg+""]
    
    If config['variable'] exists:
        do something...

arg is the section name that I give my script as a parameter.


Solution

  • import configparser
    
    spam = 'some_section'
    eggs = 'some_key'
    config = configparser.ConfigParser()
    config.read('config.cfg')
    if config.has_option(spam, eggs):
        # do something
    
    # alternative
    
    if config.get(spam, eggs, fallback=None):
       # do something
    

    you can use has_option() or get()