【问题标题】:How to use a CLI argument after subcommand with the structopt crate?如何在带有 structopt crate 的子命令之后使用 CLI 参数?
【发布时间】:2020-01-22 20:51:58
【问题描述】:

例如,使用

运行我的应用程序
./app --foo=bar get

效果很好,但是

./app get --foo=bar

产生错误:

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

USAGE:
    app --foo <foo> get

代码:

use structopt::*;

#[derive(Debug, StructOpt)]
#[structopt(name = "app")]
struct CliArgs {
    #[structopt(long)]
    foo: String,
    #[structopt(subcommand)]
    cmd: Cmd,
}

#[derive(Debug, StructOpt)]
enum Cmd {
    Get,
    Set,
}

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

依赖关系:

structopt = { version = "0.3", features = [ "paw" ] }
paw = "1.0"

【问题讨论】:

    标签: rust command-line-arguments structopt


    【解决方案1】:

    根据issue 237,有一个global参数。没想到,文档中没有提到。

    使用global = true 效果很好:

    use structopt::*;
    
    #[derive(Debug, StructOpt)]
    #[structopt(name = "cli")]
    struct CliArgs {
        #[structopt(
            long,
            global = true,
            default_value = "")]
        foo: String,
        #[structopt(subcommand)]
        cmd: Cmd,
    }
    
    #[derive(Debug, StructOpt)]
    enum Cmd {
        Get,
        Set,
    }
    
    fn main() {
        let args = CliArgs::from_args();
        println!("{:?}", args);
    }
    

    请注意,全局参数必须是可选的或具有默认值。

    【讨论】:

    • global 在文档中没有提到,因为它是一个拍手功能。但据记载,#[structopt(...)] 支持拍手方法。
    【解决方案2】:

    您需要为每个具有参数的命令枚举变体提供另一个结构:

    use structopt::*; // 0.3.8
    
    #[derive(Debug, StructOpt)]
    struct CliArgs {
        #[structopt(subcommand)]
        cmd: Cmd,
    }
    
    #[derive(Debug, StructOpt)]
    enum Cmd {
        Get(GetArgs),
        Set,
    }
    
    #[derive(Debug, StructOpt)]
    struct GetArgs {
        #[structopt(long)]
        foo: String,
    }
    
    fn main() {
        let args = CliArgs::from_args();
        println!("{:?}", args);
    }
    
    ./target/debug/example get --foo=1
    CliArgs { cmd: Get(GetArgs { foo: "1" }) }
    

    【讨论】:

      猜你喜欢
      • 2018-11-13
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多