Re: writing command-line options into file

2011-03-14 Thread Steven D'Aprano
On Mon, 14 Mar 2011 05:13:37 -0700, hiral wrote:

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


What is parser?


> 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

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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing command-line options into file

2011-03-14 Thread Brian Blais

On Mar 14, 2011, at 8:13 AM, hiral wrote:

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

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
bbl...@bryant.edu
http://web.bryant.edu/~bblais
http://bblais.blogspot.com/



-- 
http://mail.python.org/mailman/listinfo/python-list