why args.add_argument works when given in two separate statements but not one in python?

谁都会走 提交于 2019-12-05 13:28:36

You're not doing the same thing. Look at the docs:

name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.

You can't specify a list of positional arguments, just a single positional argument, or a list of option (flag) arguments. So, when you try to give it 'bar', '--foo', it tries to parse 'bar' as an option, and it can't, because it doesn't start with a -.

And, as the next section explains, when you give it a list of options, you're giving it a list of alternative names for the same flag, not a bunch of separate flags. So, you don't want to do what you're trying to do in the first place.

add_argument is meant to add a single argument. 'bar' is one positional argument; '--foo' is one optional argument. You can't make an argument that is both positional and optional, hence the error.

If you want to define an argument, but name the option differently, use dest:

# accept an option --foo X, and store X into args.bar
parser.add_argument('--foo', dest='bar')

Note that you can define multiple aliases for a single optional argument, e.g.

parser.add_argument('-f', '--foo', '--frobnicate')

So you're giving argparse two totally different ways of defining an argument. So it's throwing an error because it can't understand your input

One method of defining an argument is using no dashes like you had first

parser.add_argument("bar")  # This is a required argument

Another is to use dashes

parser.add_argument("-f", "--foo")  

--foo is just another way of specifying the same argument as -f. It is not a required argument like ones with no dashes (bar) unless you want it to be a required argument

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