![](/img/trans.png)
[英]How to use StructOpt to parse an argument into a Vec without it being treated as multiple arguments?
[英]How to use a CLI argument after subcommand with the structopt crate?
例如,运行我的应用程序
./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"
根据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);
}
请注意,全局参数必须是可选的或具有默认值。
您需要为每个具有参数的命令枚举变体提供另一个结构:
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" }) }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.