[argparse] optional parameter without --switch
Peter Otten
__peter__ at web.de
Tue Nov 24 03:36:38 EST 2015
c.buhtz at 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
More information about the Python-list
mailing list