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...

    output_file:
    MY_OPTION1 123
    YOUR_OPTION2 abc
    FLAG True

    OR
    output_file:
    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
    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):
    data=self.defaults
    with open(fname,'w') as fid:
    yaml.dump(data,fid,default_flow_style=False)

    def load(self,fname):
    data=yaml.load(open(fname))
    for option in data:
    self.add_option("--"+option,default=data[option])



    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)


    parser.save('test.yaml')


    newparser=MyOptionParser()
    newparser.load('test.yaml')


    bb
     
    Brian Blais, Mar 14, 2011
    #2
    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)
    ofile.close()
     
    Steven D'Aprano, Mar 14, 2011
    #3
    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.