Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Argparse expected one argument

I have the following

import argparse

parser = argparse.ArgumentParser(prog='macc', usage='macc [options] [address]')
parser.add_argument('-l', '--list', help='Lists MAC Addresses')
args = parser.parse_args()
print(args)

def list_macs():
  print("Found the following MAC Addresses")

I get an error when running with python macc.py -l it says that an argument was expected. Even when I change my code to parser.add_argument('-l', '--list', help='Lists MAC Addresses' default=1) I get the same error.

like image 430
Jordan Baron Avatar asked Dec 16 '19 19:12

Jordan Baron


1 Answers

The default action for an argument is store, which sets the value of the attribute in the namespace returned by parser.parse_args using the next command line argument.

You don't want to store any particular value; you just want to acknowledge that -l was used. A quick hack would be to use the store_true action (which would set args.list to True).

parser = argparse.ArgumentParser(prog='macc')
parser.add_argument('-l', '--list', action='store_true', help='Lists MAC Addresses')

args = parser.parse_args()

if args.list:
    list_macs()

The store_true action implies type=bool and default=False as well.


However, a slightly cleaner approach would be to define a subcommand named list. With this approach, your invocation would be macc.py list rather than macc.py --list.

parser = argparse.ArgumentParser(prog='macc')
subparsers = parser.add_subparsers(dest='cmd_name')
subparsers.add_parser('list')

args = parser.parse_args()

if args.cmd_name == "list":
    list_macs()
like image 176
chepner Avatar answered Oct 11 '22 19:10

chepner