[Python] Passing config file as argument to config parse module

Discussão em 'Python' iniciado por Stack, Junho 24, 2025.

  1. Stack

    Stack Membro Participativo

    My script should be called like thiks:

    # python start.py --config=start.cfg


    So I've got three files:

    start.py

    import argparse
    import options

    parser = argparse.ArgumentParser(prog='mystart')
    parser.add_argument("-f", "--file", dest="filename",
    help="write report to FILE", metavar="FILE")

    args = parser.parse_args()
    ConfigFile = args.filename

    test = options.getTest()

    print test


    options.py

    from ConfigReader import getConfigValue as getVal


    def getTest():
    Test = getVal('main', 'test')
    return Test


    ConfigReader.py

    import os
    import ConfigParser


    def config():
    cfg = ConfigParser.ConfigParser()
    for f in ('default.cfg',):
    if os.path.exists(f):
    cfg.read(f)
    return cfg
    return None


    def getConfigValue(Section, Option):
    cfg = config()
    if cfg.has_option(Section, Option):
    return cfg.get(Section, Option)
    else:
    return None


    As you can see my config file is hard coded in my module ConfigReader.py. How can I pass now my var ConfigFile into my module?

    This is just a simple example. I have a hole bunch of files which should access this variable also.

    Is a global variable an option? Is there another way?

    Continue reading...

Compartilhe esta Página