Argparse expected one argument

人盡茶涼 提交于 2021-01-02 06:15:39

问题


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.


回答1:


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()



回答2:


If you use the argument -l on the cli you need to specify an argument, like:

python macc.py -l something

If you set default = 1 on the -l argument you can run your script without using it like this:

python macc.py


来源:https://stackoverflow.com/questions/59363298/argparse-expected-one-argument

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!