Issue
i want to use the optional arguments without -
or --
,
want to achive something like this:
scriptname install <other options>
scriptname uninstall <other options>
my code:
parser = argparse.ArgumentParser()
parser.add_argument("install","INSTALL",action='store_true',help="INSTALL SOMETHING",default="")
parser.add_argument("uninstall","UNINSTALL",action='store_true',help="UNINSTALL SOMETHING",default="")
args = parser.parse_args()
if args.install:
install logic
if args.uninstall:
uninstall logic
getting the error below
ValueError: invalid option string 'install': must start with a character '-'
Solution
A 'store_true' action does not take any arguments (nargs=0
). A positional with that action is always true. And it will reject commandline strings like 'install' as unrecognized.
The dash is part of the definition of an optional
. It identifies strings that serve as flags or names, as opposed to values. Without it you are defining a positional
, an argument that is identified by position rather than a flag string.
So the normal optionals
definitions would be:
parser.add_argument("--install",action='store_true',help="INSTALL SOMETHING")
parser.add_argument("--uninstall",action='store_true',help="UNINSTALL SOMETHING")
You could put those in a mutually exclusive group. With store_true
the default is False
, and if the flag is provided, without any argument, the attribute is set of True.
store_true
is allowed with positionals, but doesn't make sense. A positional is required, so you can't get a False
value.
You could define a positional with choices:
parser.add_argument('foo', choices=['install', 'uninstall'], help='...')
Then args.foo
will have ones of those two string values.
The suggested use of subparsers
is a variant on this choices positional - one where the action
type is a special one that triggers a new parser.
Answered By - hpaulj
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.