TypeError: 'required' is an invalid argument for positionals

Question:

I want to give optional arguments to my Python3 code. I am using argparse


def main():

    parser = argparse.ArgumentParser(description="Solution")
    parser.add_argument("size", help="sector size")
    parser.add_argument("name", help="Disk name", required = False)
    args = parser.parse_args()

    sec_size = args.size
    if not args.name :
        print('Will carry only few sets of operations')
    else :
        name = args.name


It is giving error

Traceback (most recent call last):
  File "pythoncode.py", line 189, in <module>
    main()
  File "pythoncode.py", line 145, in main
    parser.add_argument("name", help="Disk name", required = False)
  File "/usr/lib64/python3.7/argparse.py", line 1335, in add_argument
    kwargs = self._get_positional_kwargs(*args, **kwargs)
  File "/usr/lib64/python3.7/argparse.py", line 1447, in _get_positional_kwargs
    raise TypeError(msg)
TypeError: 'required' is an invalid argument for positionals

Could someone please point what am I doing wrong here?
Thank you.

Asked By: gkr2d2

||

Answers:

Required=false can be used for only optional argemnts. And for optional arguments you should use —

parser.add_argument("--name", help="Disk name", required = False)

When there is no -- the python considers it as a positional argument. so the functional argument required is invalid for positional arguements

Answered By: ArunJose

You can make optional positional arguments with nargs='?' instead of required=False.

parser.add_argument("name", help="Disk name", nargs='?')
Answered By: John Henckel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.