Home > other >  ConfigParser: Check If variable in Config File exists
ConfigParser: Check If variable in Config File exists

Time:01-25

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.

CodePudding user response:

import configparser

spam = 'some_section'
eggs = 'some_key'
config = configparser.ConfigParser()
config.read('config.cfg')
if config.has_option(spam, eggs):
    # do somethong

# alternative

if config.get(spam, eggs, fallback=None):
   # do something

you can use has_option() or get()

  •  Tags:  
  • Related