问题:检查是否设置了argparse可选参数
我想检查用户是否设置了可选的argparse参数。
我可以安全地使用isset检查吗?
像这样:
if(isset(args.myArg)):
#do something
else:
#do something else
这对于float / int / string类型参数是否起作用?
我可以设置一个默认参数并检查它(例如,设置myArg = -1,或为字符串““或“ NOT_SET”)。但是,我最终要使用的值仅在脚本的稍后部分计算。因此,我会将其默认设置为-1,然后稍后将其更新为其他内容。与仅检查该值是否由用户设置相比,这似乎有点笨拙。
I would like to check whether an optional argparse argument has been set by the user or not.
Can I safely check using isset?
Something like this:
if(isset(args.myArg)):
#do something
else:
#do something else
Does this work the same for float / int / string type arguments?
I could set a default parameter and check it (e.g., set myArg = -1, or “” for a string, or “NOT_SET”). However, the value I ultimately want to use is only calculated later in the script. So I would be setting it to -1 as a default, and then updating it to something else later. This seems a little clumsy in comparison with simply checking if the value was set by the user.
回答 0
我认为,如果未提供可选参数(用指定--
),None
则将其初始化。因此,您可以使用进行测试is not None
。请尝试以下示例:
import argparse as ap
def main():
parser = ap.ArgumentParser(description="My Script")
parser.add_argument("--myArg")
args, leftovers = parser.parse_known_args()
if args.myArg is not None:
print "myArg has been set (value is %s)" % args.myArg
I think that optional arguments (specified with --
) are initialized to None
if they are not supplied. So you can test with is not None
. Try the example below:
import argparse as ap
def main():
parser = ap.ArgumentParser(description="My Script")
parser.add_argument("--myArg")
args, leftovers = parser.parse_known_args()
if args.myArg is not None:
print "myArg has been set (value is %s)" % args.myArg
回答 1
正如@Honza所说,这is None
是一个很好的测试。这是默认设置default
,用户无法给您提供重复的字符串。
您可以指定另一个default='mydefaultvalue
,然后进行测试。但是,如果用户指定该字符串怎么办?是否算作设置?
您也可以指定default=argparse.SUPPRESS
。然后,如果用户不使用该参数,它将不会出现在args
命名空间中。但是测试可能会更复杂:
args.foo # raises an AttributeError
hasattr(args, 'foo') # returns False
getattr(args, 'foo', 'other') # returns 'other'
内部parser
保留一个的列表seen_actions
,并将其用于“必需”和“互斥”测试。但您无法使用parse_args
。
As @Honza notes is None
is a good test. It’s the default default
, and the user can’t give you a string that duplicates it.
You can specify another default='mydefaultvalue
, and test for that. But what if the user specifies that string? Does that count as setting or not?
You can also specify default=argparse.SUPPRESS
. Then if the user does not use the argument, it will not appear in the args
namespace. But testing that might be more complicated:
args.foo # raises an AttributeError
hasattr(args, 'foo') # returns False
getattr(args, 'foo', 'other') # returns 'other'
Internally the parser
keeps a list of seen_actions
, and uses it for ‘required’ and ‘mutually_exclusive’ testing. But it isn’t available to you out side of parse_args
.
回答 2
我认为使用该选项default=argparse.SUPPRESS
最有意义。然后,而不是检查参数是否为,而是检查参数是否not None
为in
为结果命名空间。
例:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo", default=argparse.SUPPRESS)
ns = parser.parse_args()
print("Parsed arguments: {}".format(ns))
print("foo in namespace?: {}".format("foo" in ns))
用法:
$ python argparse_test.py --foo 1
Parsed arguments: Namespace(foo='1')
foo in namespace?: True
不提供参数:
$ python argparse_test.py
Parsed arguments: Namespace()
foo in namespace?: False
I think using the option default=argparse.SUPPRESS
makes most sense. Then, instead of checking if the argument is not None
, one checks if the argument is in
the resulting namespace.
Example:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--foo", default=argparse.SUPPRESS)
ns = parser.parse_args()
print("Parsed arguments: {}".format(ns))
print("foo in namespace?: {}".format("foo" in ns))
Usage:
$ python argparse_test.py --foo 1
Parsed arguments: Namespace(foo='1')
foo in namespace?: True
Argument is not supplied:
$ python argparse_test.py
Parsed arguments: Namespace()
foo in namespace?: False
回答 3
您可以使用store_true
和store_false
参数操作选项检查可选传递的标志:
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument('-flag', dest='flag_exists', action='store_true')
print argparser.parse_args([])
# Namespace(flag_exists=False)
print argparser.parse_args(['-flag'])
# Namespace(flag_exists=True)
这样,您就不必担心按条件检查is not None
。您只需检查True
或False
。在此处阅读更多关于这些选项的信息
You can check an optionally passed flag with store_true
and store_false
argument action options:
import argparse
argparser = argparse.ArgumentParser()
argparser.add_argument('-flag', dest='flag_exists', action='store_true')
print argparser.parse_args([])
# Namespace(flag_exists=False)
print argparser.parse_args(['-flag'])
# Namespace(flag_exists=True)
This way, you don’t have to worry about checking by conditional is not None
. You simply check for True
or False
. Read more about these options in the docs here
回答 4
如果您的参数是位置参数(即,它没有“-”或“-”前缀,只有参数,通常是文件名),则可以使用nargs参数执行此操作:
parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename is not None:
print('The file name is {}'.format(args.filename))
else:
print('Oh well ; No args, no problems')
If your argument is positional (ie it doesn’t have a “-” or a “–” prefix, just the argument, typically a file name) then you can use the nargs parameter to do this:
parser = argparse.ArgumentParser(description='Foo is a program that does things')
parser.add_argument('filename', nargs='?')
args = parser.parse_args()
if args.filename is not None:
print('The file name is {}'.format(args.filename))
else:
print('Oh well ; No args, no problems')
回答 5
这是我的解决方案,看看我是否正在使用argparse变量
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-1", "--first", required=True)
ap.add_argument("-2", "--second", required=True)
ap.add_argument("-3", "--third", required=False)
# Combine all arguments into a list called args
args = vars(ap.parse_args())
if args["third"] is not None:
# do something
这可能会使我对上面的答案有更深入的了解,而我使用该答案并对其进行了修改以使其适合我的程序。
Here is my solution to see if I am using an argparse variable
import argparse
ap = argparse.ArgumentParser()
ap.add_argument("-1", "--first", required=True)
ap.add_argument("-2", "--second", required=True)
ap.add_argument("-3", "--third", required=False)
# Combine all arguments into a list called args
args = vars(ap.parse_args())
if args["third"] is not None:
# do something
This might give more insight to the above answer which I used and adapted to work for my program.
回答 6
为了解决@kcpr对@Honza Osobne的(当前接受的)答案的评论
不幸的是,它不起作用,然后参数将其定义为默认值。
首先可以通过将参数与 Namespace
提供default=argparse.SUPPRESS
选项对象abd(请参见@hpaulj和@Erasmus Cedernaes的答案以及此python3 doc),如果未提供参数,则将其设置为默认值。
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--infile', default=argparse.SUPPRESS)
args = parser.parse_args()
if 'infile' in args:
# the argument is in the namespace, it's been provided by the user
# set it to what has been provided
theinfile = args.infile
print('argument \'--infile\' was given, set to {}'.format(theinfile))
else:
# the argument isn't in the namespace
# set it to a default value
theinfile = 'your_default.txt'
print('argument \'--infile\' was not given, set to default {}'.format(theinfile))
用法
$ python3 testargparse_so.py
argument '--infile' was not given, set to default your_default.txt
$ python3 testargparse_so.py --infile user_file.txt
argument '--infile' was given, set to user_file.txt
In order to address @kcpr’s comment on the (currently accepted) answer by @Honza Osobne
Unfortunately it doesn’t work then the argument got it’s default value
defined.
one can first check if the argument was provided by comparing it with the Namespace
object abd providing the default=argparse.SUPPRESS
option (see @hpaulj’s and @Erasmus Cedernaes answers and this python3 doc) and if it hasn’t been provided, then set it to a default value.
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--infile', default=argparse.SUPPRESS)
args = parser.parse_args()
if 'infile' in args:
# the argument is in the namespace, it's been provided by the user
# set it to what has been provided
theinfile = args.infile
print('argument \'--infile\' was given, set to {}'.format(theinfile))
else:
# the argument isn't in the namespace
# set it to a default value
theinfile = 'your_default.txt'
print('argument \'--infile\' was not given, set to default {}'.format(theinfile))
Usage
$ python3 testargparse_so.py
argument '--infile' was not given, set to default your_default.txt
$ python3 testargparse_so.py --infile user_file.txt
argument '--infile' was given, set to user_file.txt
回答 7
很简单,在通过“ args = parser.parse_args()”定义args变量后,它也包含args子集变量的所有数据。要检查是否设置了变量或假设使用的是’action =“ store_true” …
if args.argument_name:
# do something
else:
# do something else
Very simple, after defining args variable by ‘args = parser.parse_args()’ it contains all data of args subset variables too. To check if a variable is set or no assuming the ‘action=”store_true” is used…
if args.argument_name:
# do something
else:
# do something else