gpt4 book ai didi

F#:使用 Argu 时出现 --help 参数的异常

转载 作者:行者123 更新时间:2023-12-01 06:24:32 25 4
gpt4 key购买 nike

我对 F# 非常陌生,我正在尝试创建一个接受参数的控制台应用程序。我找到了Argu图书馆,并一直试图让一个基本的例子工作。如果传递了 --commanda--commandb 参数,则以下内容按预期工作,但如果我尝试 --help,则会出现异常。

open System
open Argu

type CliArguments =
| CommandA
| CommandB
with
interface IArgParserTemplate with
member s.Usage =
match s with
| CommandA -> "CommandA - Do something"
| CommandB -> "CommandB - Do something"

[<EntryPoint>]
let main argv =

let parser = ArgumentParser.Create<CliArguments>()
let results = parser.Parse argv

results.GetAllResults()
|> List.iter (fun x ->
match x with
| CommandA -> printfn "CommandA"
| CommandB -> printfn "CommandB")

0

异常(exception)是:

> .\Argu_sample.exe --help

Unhandled Exception: Argu.ArguParseException: USAGE: Argu_sample.exe [--help] [--commanda] [--commandb]

OPTIONS:

--commanda CommandA - Do something
--commandb CommandB - Do something
--help display this list of options.

at Argu.ExceptionExiter.Argu-IExiter-Exit[a](String msg, ErrorCode errorCode)
at Argu.ArgumentParser`1.Parse(FSharpOption`1 inputs, FSharpOption`1 configurationReader, FSharpOption`1 ignoreMissing, FSharpOption`1 ignoreUnrecognized, FSharpOption`1 raiseOnUsage)
at Program.main(String[] argv) in C:\Data\FSharp\Argu-sample\Argu-sample\Program.fs:line 18

我做错了什么?

谢谢。

使用解决方案更新代码:

根据 AMieres 的评论,我最终使用了 try with:

open System
open Argu

type CliArguments =
| CommandA
| CommandB
with
interface IArgParserTemplate with
member s.Usage =
match s with
| CommandA -> "CommandA - Do something"
| CommandB -> "CommandB - Do something"

[<EntryPoint>]
let main argv =

let parser = ArgumentParser.Create<CliArguments>()

try
let results = parser.Parse argv

results.GetAllResults()
|> List.iter (fun x ->
match x with
| CommandA -> printfn "CommandA"
| CommandB -> printfn "CommandB")
0
with
| :? ArguParseException as ex ->
printfn "%s" ex.Message
1
| ex ->
printfn "Internal Error:"
printfn "%s" ex.Message
2

最佳答案

我似乎是一个未记录的功能。--help 被视为异常,您需要使用 try with 处理它或提供处理程序。

查看 Github 中的示例:https://github.com/fsprojects/Argu/blob/master/samples/Argu.Samples.LS/Program.fs .

在其中,解析器是使用错误处理程序创建的:

let errorHandler = ProcessExiter(colorizer = function ErrorCode.HelpText -> None | _ -> Some ConsoleColor.Red)
let parser = ArgumentParser.Create<LsArguments>(programName = "ls", errorHandler = errorHandler)

如有疑问,请查阅代码: https://github.com/fsprojects/Argu/blob/b1569917af314dfd3b77fb79fec2a157a51324c7/src/Argu/Types.fs#L29

/// Error codes reported by Argu
type ErrorCode =
| HelpText = 0
| AppSettings = 1
| CommandLine = 2
| PostProcess = 3

关于F#:使用 Argu 时出现 --help 参数的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54378989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com