Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #99300 > unrolled thread

Re: [argparse] optional parameter without --switch

Started byPeter Otten <__peter__@web.de>
First post2015-11-24 09:36 +0100
Last post2015-11-24 09:36 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: [argparse] optional parameter without --switch Peter Otten <__peter__@web.de> - 2015-11-24 09:36 +0100

#99300 — Re: [argparse] optional parameter without --switch

FromPeter Otten <__peter__@web.de>
Date2015-11-24 09:36 +0100
SubjectRe: [argparse] optional parameter without --switch
Message-ID<mailman.93.1448354220.2291.python-list@python.org>
c.buhtz@posteo.jp wrote:

> I want to call (on bash) a Python script in this two ways without any
> error.
> 
>     ./arg.py
>     ./arg.py TEST
> 
> It means that the parameter (here with the value `TEST`) should be
> optional. With argparse I only know a way to create optional paramters
> when they have a switch (like `--name`).

$ cat tmp.py
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("name", nargs="?")
print("name =", parser.parse_args().name)
$ ./tmp.py
name = None
$ ./tmp.py 42
name = 42

https://docs.python.org/dev/library/argparse.html#nargs

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web