How to read only some sections of a config file

Viewed 42

I want to access client_name, client_id and payment_id for each of the clients in the client list in order to start start a few processed using multithreading. I have included my config file and the way I am trying to access it. I found how to iterate over all sections, but don't know how to access just some of them. Any help is appreciated.

cfg = configparser.ConfigParser(allow_no_value=True)
cfg.read('config.ini')
customer_url=cfg.get('general', 'url')

 
def process(client_name, client_id, payment_id):
    print("process()")
    clients=cfg['clients']
    client_list=cfg['clients']['client_list']
    

    for client in client_list:
        
       
       client_name = cfg.get(clients,'client_name')
       client_id=cfg.get(clients, 'client_id')
       payment_id =cfg.get(clients, 'payment_id')
       
    
    for _ in range(len(clients[client_list])):
         thread=threading.Thread(target=process, args=[client_name, client_id, payment_id])
         thread.start()
[clients]
client_list= xxx, yyy,zzz

[general]

DB_HOSTNAME = localhost
DB = asass
DB_USERNAME =asasasas
DB_PASSWORD = ddddddd
DB_PORT = 3307
url=https://something.com

[xxx]
client_name = xxx
client_id = 24
payment_id = 26



[yyy]
client_name = yyy
client_id = 12
payment_id = 45


[zzz]
client_name = zzz
client_id = 4545
payment_id = 46

1 Answers

Just look them up, since you have the keys:

clients=[x.strip() for x in cfg['clients']['client_list'].split(",")]
for client in clients:
    details = cfg[client]
    do_stuff(details)

Or do the lookup in the listcomp:

clients = [cfg[x.strip()] for x in cfg["clients"]["client_list"].split(",")]
for client in clients:
    do_stuff(client)

With that said there are some very odd things about your code. Don't launch a thread by pointing it to the current function---that creates infinite recursion. I've no idea why you want to multithread this anyhow. Certainly just parsing the data shouldn't be threaded: it'll take longer to set up/serialise than just to do it sequentially.

Related