Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: Newsgroups: comp.lang.python Subject: [argparse] optional parameter without --switch Date: Mon, 23 Nov 2015 18:04:01 +0100 Lines: 32 Message-ID: Mime-Version: 1.0 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: 7bit X-Trace: news.uni-berlin.de Mdtm28M2ado+f8qqLc4YJwqi6Ldl3XMO0TDGSEvlkgPQ== Return-Path: X-Original-To: python-list@python.org Delivered-To: python-list@mail.python.org X-Spam-Status: OK 0.001 X-Spam-Evidence: '*H*': 1.00; '*S*': 0.00; 'python3': 0.05; 'sys': 0.05; 'that?': 0.05; 'namespace': 0.09; 'optional': 0.09; 'received:172.16.0': 0.09; 'skip:# 30': 0.09; 'python': 0.10; 'skip:# 20': 0.13; 'argparse': 0.16; 'received:io': 0.16; 'received:psf.io': 0.16; 'subject:argparse': 0.16; 'subject:] ': 0.19; 'fix': 0.21; '(on': 0.22; 'arguments': 0.22; 'parameter': 0.22; 'parser': 0.22; '(like': 0.23; 'skip:l 40': 0.23; 'import': 0.24; 'script': 0.25; 'skip:# 10': 0.27; 'switch': 0.27; 'optional.': 0.29; 'error.': 0.31; 'but': 0.36; 'should': 0.36; 'there': 0.36; 'to:addr:python-list': 0.36; 'two': 0.37; 'charset :us-ascii': 0.37; 'means': 0.39; 'subject:[': 0.39; 'test': 0.39; 'to:addr:python.org': 0.40; 'received:de': 0.40; 'from:no real name:2**0': 0.60; 'header:Message-Id:1': 0.61; 'skip:a 40': 0.64; 'received:185': 0.91 X-Mailer: Claws Mail 3.9.3 (GTK+ 2.24.23; i686-pc-linux-gnu) X-Mailman-Approved-At: Tue, 24 Nov 2015 01:03:37 -0500 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:99297 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`). Is there a way to fix that? #!/usr/bin/env python3 import sys import argparse parser = argparse.ArgumentParser(description=__file__) # must have #parser.add_argument('name', metavar='NAME', type=str) # optional BUT with a switch I don't want #parser.add_argument('--name', metavar='NAME', type=str) # store all arguments in objects/variables of the local namespace locals().update(vars(parser.parse_args())) print(name) sys.exit() -- GnuPGP-Key ID 0751A8EC