writing command-line options into file

Discussion in 'Python' started by hiral, Mar 14, 2011.

  1. hiral

    hiral Guest

    For following example, how to write command-line option OR metavar
    into file...

    parser.add_option("-opt1", metavar="MY_OPTION1", default=123)
    parser.add_option("-opt2", metavar="YOUR_OPTION2" ,default= "abc")
    parser.add_option('-opt3", metavar="FLAG", default=True)

    do we have any facility to write command-line option OR 'metavar' into
    file as follow...

    MY_OPTION1 123
    YOUR_OPTION2 abc
    FLAG True

    opt1 123
    opt2 abc
    opt3 True

    Any idea?

    Please note that in actual application there are about 80 to 90
    command-line options.

    Thank you in advance.
    hiral, Mar 14, 2011
    1. Advertisements

  2. hiral

    Brian Blais Guest

    Perhaps something like this would work. This loads and saves just the default values. A little more digging could make it more robust, and inclusive. The output file (test.yaml) looks like:

    opt1: 123
    opt2: abc
    opt3: true

    from __future__ import with_statement
    from optparse import OptionParser
    import yaml

    class MyOptionParser(OptionParser):

    def save(self,fname):
    with open(fname,'w') as fid:

    def load(self,fname):
    for option in data:

    parser = MyOptionParser()

    parser.add_option("--opt1", metavar="MY_OPTION1", default=123)
    parser.add_option("--opt2", metavar="YOUR_OPTION2" ,default= "abc")
    parser.add_option("--opt3", metavar="FLAG", default=True)



    Brian Blais, Mar 14, 2011
    1. Advertisements

  3. What is parser?

    Write a helper function like this:

    def opt_writer(f, parser, *args, **kwargs):
    parser.add_option(*args, **kwargs)
    template = "%(metavar)s %(default)s\n"
    f.write(template % kwargs)

    then call it:

    ofile = open('output.txt', 'w')
    opt_writer(ofile, parser, "-opt1", metavar="MY_OPTION1", default=123)
    opt_writer(ofile, parser, "-opt2", metavar="YOUR_OPTION2" ,default= "abc")
    opt_writer(ofile, parser, "-opt3", metavar="FLAG", default=True)
    Steven D'Aprano, Mar 14, 2011
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.