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


Groups > comp.lang.python > #99300

Re: [argparse] optional parameter without --switch

From Peter Otten <__peter__@web.de>
Newsgroups comp.lang.python
Subject Re: [argparse] optional parameter without --switch
Date 2015-11-24 09:36 +0100
Organization None
Message-ID <mailman.93.1448354220.2291.python-list@python.org> (permalink)
References <3p4FFS0cRdz5vNy@dovecot03.posteo.de>

Show all headers | View raw


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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

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

csiph-web