Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'required' is an invalid argument for positionals in python command

I want to implement import feature with required and optional parameters, to run this in this way:

python manage.py import --mode archive

where --mode is required and archive also.

I'm using argparse library.

class Command(BaseCommand):
    help = 'Import'

    def add_arguments(self, parser):
        parser.add_argument('--mode',
            required=True,
        )
        parser.add_argument('archive',
            required=True,
            default=False,
            help='Make import archive events'
        )

But I recived error:

TypeError: 'required' is an invalid argument for positionals
like image 739
Kai Avatar asked Jul 13 '17 10:07

Kai


People also ask

How do you add an optional argument in Argparse?

To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.

How do you add an argument in Python?

To add arguments to Python scripts, you will have to use a built-in module named “argparse”. As the name suggests, it parses command line arguments used while launching a Python script or application. These parsed arguments are also checked by the “argparse” module to ensure that they are of proper “type”.

How do you make a positional argument optional in Python?

You can assign an optional argument using the assignment operator in a function definition or using the Python **kwargs statement. There are two types of arguments a Python function can accept: positional and optional. Optional arguments are values that do not need to be specified for a function to be called.


2 Answers

You created a positional argument (no -- option in front of the name). Positional arguments are always required. You can't use required=True for such options, just drop the required. Drop the default too; a required argument can't have a default value (it would never be used anyway):

parser.add_argument('archive',
    help='Make import archive events'
)

If you meant for archive to be a command-line switch, use --archive instead.

like image 94
Martijn Pieters Avatar answered Oct 13 '22 03:10

Martijn Pieters


I think that --mode archive is supposed to mean "mode is archive", in other words archive is the value of the --mode argument, not a separate argument. If it were, it would have to be --archive which is not what you want.

Just leave out the definition of archive.

like image 25
BoarGules Avatar answered Oct 13 '22 03:10

BoarGules