Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Peter Otten <__peter__@web.de> Newsgroups: comp.lang.python Subject: Re: [argparse] optional parameter without --switch Date: Tue, 24 Nov 2015 09:36:38 +0100 Organization: None Lines: 25 Message-ID: References: <3p4FFS0cRdz5vNy@dovecot03.posteo.de> Mime-Version: 1.0 Content-Type: text/plain; charset="ISO-8859-1" Content-Transfer-Encoding: 7Bit X-Trace: news.uni-berlin.de AaHC2jyUU3YPVXFcIV2kuggbyVQh988rWZ0oevqTaAYg== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.000 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'subject:: [': 0.03; 'python3': 0.05; 'optional': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'python': 0.10; 'argparse': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:io': 0.16; 'received:plane.gmane.org': 0.16; 'received:psf.io': 0.16; 'received:t-ipconnect.de': 0.16; 'subject:argparse': 0.16; 'wrote:': 0.16; 'subject:] ': 0.19; '(on': 0.22; 'parameter': 0.22; 'parser': 0.22; '(like': 0.23; 'import': 0.24; 'script': 0.25; 'header:User-Agent:1': 0.26; 'header:X-Complaints-To:1': 0.26; 'skip:# 10': 0.27; 'switch': 0.27; 'cat': 0.29; 'optional.': 0.29; 'error.': 0.31; 'url:python': 0.33; 'url:dev': 0.35; 'should': 0.36; 'url:org': 0.36; 'url:library': 0.36; 'to:addr:python-list': 0.36; 'two': 0.37; 'received:org': 0.37; 'skip:p 20': 0.38; 'means': 0.39; 'test': 0.39; 'to:addr:python.org': 0.40; 'received:de': 0.40 X-Injected-Via-Gmane: http://gmane.org/ X-Gmane-NNTP-Posting-Host: p57bd99e9.dip0.t-ipconnect.de User-Agent: KNode/4.13.3 X-BeenThere: python-list@python.org X-Mailman-Version: 2.1.20+ Precedence: list List-Id: General discussion list for the Python programming language List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , Xref: csiph.com comp.lang.python:99300 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