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
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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”.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With