• # En python, c'est quand même plus simple

    Posté par . En réponse au journal Lire de fichiers de configuration depuis un script shell. Évalué à 2.

    Le fichier de config .ini :

    [DB]
    mysql.db='prout'
    mysql.host='localhost'
    mysql.user='lambda'
    mysql.password='xxxxxxx'
    [CONSOLE]
    cons.port="12443"
    cons.user="lambada"
    cons.password="xxxxxx"
    

    Le code pour parser le fichier et peupler des variables.

    #!/usr/bin/python
    import ConfigParser
    def parseConfigFile(ini):
     config = ConfigParser.ConfigParser()
     try :
     fh = config.readfp(open(ini))
     except Exception as e:
     print str(e)
     raise SystemExit(1)
     ## Fetching parameters
     try :
     mysql_db = config.get('DB', 'mysql.db')
     mysql_user = config.get('DB', 'mysql.user')
     mysql_db = config.get('DB', 'mysql.password')
     cons_port = config.get('CONSOLE', 'cons.port')
     cons_user = config.get('CONSOLE', 'cons.user')
     cons_password = config.get('CONSOLE', 'cons.password')
     except Exception as e:
     print str(e)
     raise SystemExit(1)
    parseConfigFile('cfig.ini')