【发布时间】:2016-07-19 21:12:44
【问题描述】:
这基本上与Check if argparse optional argument is set or not 相同的问题,但在 Julia 中,使用 Julia's ArgParse module。
给定一个带值的参数,我想知道它的值是否被给定。
【问题讨论】:
标签: julia argparse.jl
这基本上与Check if argparse optional argument is set or not 相同的问题,但在 Julia 中,使用 Julia's ArgParse module。
给定一个带值的参数,我想知道它的值是否被给定。
【问题讨论】:
标签: julia argparse.jl
简而言之,一旦你解析了参数,你可以检查一个参数是否被设置为parsed_args["argname"] == nothing(如果它没有设置则返回true)。
在下面找到一个独立的示例(从ArgParse.jl 略微修改example1),如果设置了参数not,则打印true(只需将== 替换为!=对于相反的行为):
using ArgParse
function main(args)
# initialize the settings (the description is for the help screen)
s = ArgParseSettings(description = "Example usage")
@add_arg_table s begin
"--opt1" # an option (will take an argument)
"arg1" # a positional argument
end
parsed_args = parse_args(s) # the result is a Dict{String,Any}
println(parsed_args["arg1"] == nothing)
println(parsed_args["opt1"] == nothing)
end
main(ARGS)
以及示例命令行调用(假设上面存储在test.jl):
>>> julia test.jl
true
true
>>> julia test.jl 5
false
true
>>> julia test.jl 5 --opt1=6
false
false
>>> julia test.jl --opt1=6
true
false
但是,有时为参数定义一个默认值可能比检查它是否已设置更合适。可以通过在参数中添加default关键字来完成:
@add_arg_table s begin
"--opt1"
"--opt2", "-o"
arg_type = Int
default = 0
"arg1"
required = true
end
以及位置参数的required关键字,这将迫使用户引入它。
【讨论】: