英文:
.NET System.CommandLine: invoking command via Parser doesn't write to console, whereas command.Invoke does
问题
我有一个控制台应用程序,它使用 System.CommandLine
解析参数和选项。
为了更好地处理异常,我已经从 RootCommand.Invoke(args)
切换到使用类似下面这样的 CommandLineBuilder:
CommandLineBuilder oCLB = new(oRootCmd);
oCLB.UseExceptionHandler((e, c) => LogExceptionAndRaiseEvent(e));
Parser oPrs = oCLB.Build();
int iRC = oPrs.Invoke(p_StartupArgs);
现在我注意到,这种调用方式不再将信息写入控制台,无论是在出现解析错误时还是在使用默认帮助开关“-h”调用时。
我怀疑与 Invoke 中的第二个参数有关,它可以是 IConsole(默认为 NULL),但我并不确定,也不知道应该传递什么值。
更新: 请参见下面的解决方案,使用了一些 CommandLineBuilder 的配置选项。
英文:
I have a console application that uses System.CommandLine
to parse arguments and options.
To be able to deal with exceptions better, I've switched from RootCommand.Invoke(args) to using a CommandLineBuilder like this:
CommandLineBuilder oCLB = new(oRootCmd);
oCLB.UseExceptionHandler((e, c) => LogExceptionAndRaiseEvent(e));
Parser oPrs = oCLB.Build();
int iRC = oPrs.Invoke(p_StartupArgs);
Now I've noticed that this way of invoking doesn't write to the console anymore, neither when there is a parsing error nor when being called with the default help switch "-h".
I suspect it has to do with the second parameter in Invoke, which is can be an IConsole (and is NULL by default), but I don't have a real clue and wouldn't know what to pass there.
UPDATE: see solution below, using some CommandLineBuilder configuration options.
答案1
得分: 0
更新,解决方案是向 CommandLineBuilder
添加了更多的“Use”配置:
CommandLineBuilder oCLB = new(oRootCmd);
oCLB.UseHelp().
UseVersionOption().
UseParseErrorReporting();
oCLB.UseExceptionHandler((e, c) => BygLog.LogExceptionAndRaiseEvent(e));
Parser oPrs = oCLB.Build();
int iRC = oPrs.Invoke(p_StartupArgs, new SystemConsole());
根据 https://github.com/dotnet/command-line-api/issues/2188
英文:
Update, the solution was adding some more "Use" configuration to the CommandLineBuilder
:
CommandLineBuilder oCLB = new(oRootCmd);
oCLB.UseHelp().
UseVersionOption().
UseParseErrorReporting();
oCLB.UseExceptionHandler((e, c) => BygLog.LogExceptionAndRaiseEvent(e));
Parser oPrs = oCLB.Build();
int iRC = oPrs.Invoke(p_StartupArgs, new SystemConsole());
As per https://github.com/dotnet/command-line-api/issues/2188
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论