0

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.

Machavity
  • 30,841
  • 27
  • 92
  • 100
  • 1
    In practice, it's often easier to fallback to a default, if the variable doesn't exist e.g. `tcp_port = config.getint('control', 'TCP_PORT', fallback=5005)` - where if the variable TCP_PORT does not exist in section 'control' the value 5005 is returned. – Rolf of Saxony Jan 25 '22 at 08:16

1 Answers1

3
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()

buran
  • 13,682
  • 10
  • 36
  • 61