簡體   English   中英

Rust:使用 Clap 解析用戶輸入字符串以進行命令行編程

[英]Rust: Parse user input String with clap for command line programming

我想創建一個利用 clap 解析輸入的命令行。 我能想到的最好的方法是一個循環,它要求用戶輸入,用正則表達式分解它並構建一個 Vec 以某種方式傳遞給

loop {
    // Print command prompt and get command
    print!("> "); io::stdout().flush().expect("Couldn't flush stdout");

    let mut input = String::new(); // Take user input (to be parsed as clap args)
    io::stdin().read_line(&mut input).expect("Error reading input.");
    let args = WORD.captures_iter(&input)
           .map(|cap| cap.get(1).or(cap.get(2)).unwrap().as_str())
           .collect::<Vec<&str>>();

    let matches = App::new("MyApp")
        // ... Process Clap args/subcommands
    .get_matches(args); //match arguments from CLI args variable
}

基本上,我想知道是否有辦法讓 Clap 使用預先給定的 arguments 列表?

正如@mcarton 所說,命令行程序將其 arguments 作為數組而不是字符串傳遞。 shell 拆分了原始命令行(考慮到引號、變量擴展等)。

如果您的要求很簡單,您可以簡單地將字符串拆分為空格並將其傳遞給 Clap。 或者,如果你想尊重帶引號的字符串,你可以使用shellwords來解析它:

let words = shellwords::split(input)?;
let matches = App::new("MyApp")
    // ... command line argument options
    .get_matches_from(words);

這就是我最終使整個工作正常進行的方式:

首先,我將整個主 function 放在一個loop中,以便它能夠獲取命令,並且,留在 CLI 中。

接下來,我通過標准輸入獲得輸入並拆分stdin

// Print command prompt and get command
print!("> ");
io::stdout().flush().expect("Couldn't flush stdout");
let mut input = String::new();
io::stdin().read_line(&mut input).expect("Error reading input.");
let args = WORD.captures_iter(&input)
           .map(|cap| cap.get(1).or(cap.get(2)).unwrap().as_str())
           .collect::<Vec<&str>>();

然后我使用 Clap 進行解析,有點像@harmic 建議的方式

let matches = App::new("MyApp")
    // ... command line argument options
    .get_matches_from(words);

並使用subcommands代替arguments

例如。

.subcommand(SubCommand::with_name("list")
    .help("Print namespaces currently tracked in the database."))

整個文件都在這里為好奇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM