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

问题描述 投票:0回答:1

我使用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,而不是被迫使用--。也许对论点的顺序做些什么呢?

rust command-line-arguments structopt
1个回答
1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.