繁体   English   中英

如何使用structopt将多出现选项与后续可选参数区分开?

[英]How can I distinguish a multi-occurence option from a subsequent optional argument with structopt?

我正在使用structopt定义可以使用的参数

mfe -s opt1 -s opt2 -s opt2 this_is_an_argument

要么

mfe -s opt1 opt2 opt3 this_is_an_argument

问题在于this_is_an_argument参数被解析为选项。 我知道我可以在争论之前使用--但是有更好的解决方案吗?

use std::path::PathBuf;
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
struct CLIArgs {
    #[structopt(short = "s", long = "str")]
    strings: Vec<String>,

    #[structopt(name = "PATH", parse(from_os_str))]
    path: Option<PathBuf>,
}

fn main() {
    let args = CLIArgs::from_args();
    println!("{:?}", args);
}
$ mfe -s foo bar baz /this/is/a/path
CLIArgs { strings: ["foo", "bar", "baz", "/this/is/a/path"], path: None }

我希望将/this/is/a/path解析为path ,而不必强制使用-- 也许按照参数的顺序执行某些操作?

所以我找到了以下解决方案:

use std::path::PathBuf;
use structopt::StructOpt;

#[derive(StructOpt, Debug)]
struct CLIArgs {
    #[structopt(short = "s", long = "str", raw(number_of_values = "1"))]
    strings: Vec<String>,

    #[structopt(name = "PATH", parse(from_os_str))]
    path: Option<PathBuf>,
}

fn main() {
    let args = CLIArgs::from_args();
    println!("{:?}", args);
}

请注意,它强制用户以这种方式使用程序:

$ mfe -s foo -s bar -s baz /this/is/a/path

根据您的使用情况,这不方便。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM