I can´t pass the arguments error: unrecognized arguments: Argparse Python3

Viewed 11479

I'm using python 3.6 and I'm trying to do a program that requires arguments, but I can not use it because I can't pass the arguments. Another question: I can't understand the dest parameter; is it to create a variable with that name?

#!/usr/bin/env python3
import argparse
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument('-m', '--mac',
                    help='Introduce your new MAC' +
                    'use random as value if you want to have a random mac',
                    action="store_true", required=True)
parser.add_argument('-i', '--interface',
                    help='The interface that the MAC will be changed',
                    action="store", required=True)
args = parser.parse_args()

print(args.mac + args.interface)

I´m getting this error, when trying to use it (I use hi and bye as examples)

> python  '.\test.py' -m hi -i bye
usage: test.py [-h] -m -i INTERFACE
test.py: error: unrecognized arguments: hi
2 Answers

As @Dawit's answer correctly points out, the issue is with action="store_true". The built-in action 'store_true' has an automatic default of False, and sets the value of the argument in the namespace to True if the flag is found. It does not accept any arguments to the flag.

If you want to accept an argument to the flag, you have to use an action like action="store".

If you want to error-check or convert your argument on the spot, pass type to add_argument. You can convert to a type like int, or just check your argument. For example, you could have a function mac_address that would be parse the argument string to a more easily managed object, or raise an error if the format didn't match. Then you could do type=mac_address.

The dest argument simply provides the name of the output attribute in the namespace to assign the value to. This is normally taken from the long name of the flag or positional argument. So for --mac the output variable would default to mac and for --interface it would default to interface. Sometimes you want to use an alternative output variable though.

This worked for me:

parser.add_argument('-m', '--mac',
                help='Introduce your new MAC' +
                'use random as value if you want to have a random mac',
                action="store", required=True

Changing store_true to store

Related