How can I pass all command line arguments through Clap to another program?

为君一笑 提交于 2019-12-24 18:53:13

问题


I have a program foo that uses Clap to handle command argument parsing. foo invokes another program, bar. Recently, I decided that users of foo should be able to pass arguments to bar if they like. I added the bar command to Clap:

let matches = App::new("Foo")
    .arg(Arg::with_name("file").value_name("FILE").required(true))
    .arg(
        Arg::with_name("bar")
            .value_name("[BAR_OPTIONS]")
            .short("b")
            .long("bar")
            .multiple(true)
            .help("Invoke bar with these options"),
    )
    .get_matches();

When I try to pass the command "-baz=3" to bar like so:

./foo -b -baz=3 file.txt

or

./foo -b "-baz=3" file.txt

clap returns this error:

error: Found argument '-b' which wasn't expected, or isn't valid in this context

How do I tunnel commands through Clap?


回答1:


If the value of argument bar may itself start with a hyphen, then you need to set the allow_hyphen_values option:

let _matches = App::new("Foo")
    .arg(Arg::with_name("file").value_name("FILE").required(true))
    .arg(
        Arg::with_name("bar")
            .value_name("[BAR_OPTIONS]")
            .allow_hyphen_values(true)
            .short("b")
            .long("bar")
            .multiple(true)
            .help("Invoke bar with these options"),
    )
    .get_matches();


来源:https://stackoverflow.com/questions/54191836/how-can-i-pass-all-command-line-arguments-through-clap-to-another-program

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