[Tutor] argparse iterable
Jason Friedman
jsf80238 at gmail.com
Tue Apr 2 03:24:04 CEST 2013
#!/usr/bin/python
import argparse
parser = argparse.ArgumentParser(description='Short sample app')
parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)
parser.parse_args()
for k,v in parser.parse_args().__dict__.items():
print('This arg is %s %s' % (k, v))
On Mon, Apr 1, 2013 at 6:31 PM, <kendy at kendy.org> wrote:
> Dear Tutor
>
> I want to compare command line options, to options in a dictionary from a
> YAML
> file. The command line will over-ride the options in my file. (The YAML
> file, and
> its dictionary are not shown. That part works.)
>
> My distilled code:
>
> -------------------------------------------------------------------------
> $ cat h.py
> #!/usr/bin/python
>
> import argparse
> parser = argparse.ArgumentParser(description='Short sample app')
>
> def GetArgs(parser):
> parser.add_argument('-a', action="store_true", default=False)
> parser.add_argument('-b', action="store", dest="b")
> parser.add_argument('-c', action="store", dest="c", type=int)
> return parser
>
> GetArgs(parser)
>
> print(parser.parse_args())
> print("But this doesn't iter through a b and c:")
> for k,v in parser.parse_args():
> print('This arg is %s %s' % k, k[str(v)])
> $
> -------------------------------------------------------------------------
>
> My error:
> $ h.py -a -b hi -c 42
> Namespace(a=True, b='hi', c=42)
> But this doesn't iter through a b and c:
> Traceback (most recent call last):
> File "./h.py", line 16, in <module>
> for k,v in parser.parse_args():
> TypeError: 'Namespace' object is not iterable
> $
>
> How can I get parser to be iterable?
>
> After I get it to iter, I suppose that I'll be bitten by the boolean and
> integer
> type conversions. I'm not sure how to handle that either. Will 'str()'
> save me?
>
> Thanks a million (again!),
> Ken
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130401/22478f4d/attachment-0001.html>
More information about the Tutor
mailing list