python - How to create an argument that is optional? -


instead of user having use script.py --file c:/stuff/file.txt there way let user optionally use --file? instead, script.py c:/stuff/file.txt parser still know user referring --file argument (because it's implied).

try this

import argparse  class donotreplaceaction(argparse.action):     def __call__(self, parser, namespace, values, option_string=none):         if not getattr(namespace, self.dest):             setattr(namespace, self.dest, values)  parser = argparse.argumentparser(description="this example.") parser.add_argument('file', nargs='?', default='', help='specifies file.', action=donotreplaceaction) parser.add_argument('--file', help='specifies file.')  args = parser.parse_args() # check file argument if not args.file:     raise exception('missing "file" argument') 

look @ message. arguments optional

usage: test.py [-h] [--file file] [file]  example.  positional arguments:   file         specifies file.  optional arguments:   -h, --help   show message , exit   --file file  specifies file. 

one thing notice positional file override optional --file , set args.file default ''. overcome used custom action positional file. forbids overriding set properties.

the other thing notice rather raising exception specify default value.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -