C#命令行參數(shù)解析庫System.CommandLine使用
命令行參數(shù)
平常在日常的開發(fā)過程中,會經(jīng)常用到命令行工具。如cmd下的各種命令。
以下為sc命令執(zhí)行后的截圖,可以看到,由于沒有輸入任何附帶參數(shù),所以程序并未執(zhí)行任何操作,只是輸出了描述和用法。
系統(tǒng)在創(chuàng)建一個新進程時,會傳一個命令行給它,也就是命令行字符串。
程序需要對命令行字符串進行解析,并執(zhí)行相應(yīng)操作。
如使用sc query可以查詢當前系統(tǒng)的服務(wù):
在C#中的控制臺程序中,Main函數(shù)中傳入的args字符串數(shù)組,就是系統(tǒng)傳入進程的命令行參數(shù)。
在構(gòu)建具有復(fù)雜命令行參數(shù)的控制臺程序時 ,手動解析參數(shù)就變得非常麻煩。這里推薦一個開源的庫,可以更加方便的解析命令行參數(shù)。
System.CommandLine介紹
System.CommandLine是一個基于.Net Standard 2.0(支持.Net FrameWork 4.6.1.2+和.Net Core 2.0+)的命令行參數(shù)解析庫,項目地址https://github.com/dotnet/command-line-api,目前,該項目還是屬于beta狀態(tài),期待以后的正式版本。
由于不是正式版本,在Nuget中引用時,需要鉤上Include prerelease,才能找到這個包。
System.CommandLine的一些基本概念
Token(標記)
命令行的每個單詞都是一個標記,如下面的"sc"、"query"和"eventlog"都是一個Token
Commands(命令)
Commands就是應(yīng)用程序根據(jù)Token執(zhí)行相應(yīng)的操作(在System.CommandLine庫中,對應(yīng) Command類)
Root Command(根命令)
根命令是代表可執(zhí)行程序本身的Commands,如 sc(在System.CommandLine庫中,對應(yīng)RootCommand類)
SubCommands(子命令)
一些命令行程序會有SubCommands,如上面的sc query中的query就是子命令(在System.CommandLine,對應(yīng)Command類)
Options(可選項)
Options就是傳遞給Commands的命名參數(shù),如 app -myoption123中的 -myoption 123就是一個Options
Argument(參數(shù))
參數(shù)就是傳遞給選項或命令的值。
說明:
常規(guī)的調(diào)用如下:
xx.exe [options] <argument> [command]
Delimiters(分隔符)
分隔符就是把Options的命令和值分開的符號
如下三種寫法都是一樣的,可以使用空格、=或 :符號
app -myoption 123
app -myoption=123
app -myoption:123
Aliases(別名)
可以為命令或選項設(shè)置較短的別名,如
-v, --verbose
--o, --option
System.CommandLine使用
在下面的示例中,我們會構(gòu)建一個簡單的控制臺爬蟲工具。
1、使用Visual Studio 2019創(chuàng)建一個.Net Core控制臺程序crawler-line
2、導(dǎo)入System.CommandLine包
3、創(chuàng)建一個RootCommand
var rootCommand = new RootCommand { new Argument<string>( "url","web site url"), new Option<bool>(new string[]{ "--gethtml" ,"-html"},"Get html source"), new Option<bool>(new string[]{ "--getimage" ,"-image"},"Get images"), new Option<bool>(new string[]{ "--regex-option" ,"-regex"},"Use regex"), new Option<bool>(new string[]{ "--htmlagilitypack-option", "-agpack"},"Use HtmlAgilityPack"), new Option<bool>(new string[]{ "--anglesharp-option", "-agsharp"},"Use AngleSharp"), new Option<string>(new string[]{ "--download-path" ,"-path"},"Designate download path"),13 };
說明:
可通過Option類的構(gòu)造函數(shù)重載,為Option指定默認值。
public Option(string alias, Func<T> getDefaultValue, string? description = null);
如上面的-path Option,指定默認值為D:\download,如下:
new Option<string>(new string[]{ "--download-path" ,"-path"},getDefaultValue:()=>"D:\\download","Designate download path"),
也可以先實例化RootCommand對象,再通過Add的方式添加Argument和Option,如下:
var rootCommand = new RootCommand(); //添加 Argument rootCommand.AddArgument(new Argument<string>("url","web site url")); //添加 Option rootCommand.AddOption(new Option<string>(new string[] {"--download-path","-path" },"download path"));
4、添加當前命令行程序的描述信息
rootCommand.Description = ".Net Core command-line crawler.";
5、解析Argument和Option
rootCommand.Handler = CommandHandler.Create<string, bool, bool, bool, bool, bool, string>((string url, bool html, bool image, bool regex, bool agpack, bool agsharp, string path) => { });
如果覺得參數(shù)太長,可以封裝成類,再進行調(diào)用,如下:
public class CrawlerOption { public string Url { get; set; } public bool GetHtml { get; set; } public bool GetImage { get; set; } public bool RegexOption { get; set; } public bool HtmlagilitypackOption { get; set; } public bool AnglesharpOption { get; set; } public string DownloadPath { get; set; } }
rootCommand.Handler = CommandHandler.Create<CrawlerOption>((crawlerOption) => { })
6、添加Command并為Command添加處理函數(shù)
//添加 Command var githubCommand = new Command("github", "fork me on github"); //添加 Command的處理函數(shù) githubCommand.Handler = CommandHandler.Create(() => { System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo("cmd", $"/c start https://github.com/zhaotianff/Crawler-Line")); }); //將Command添加 到RootCommand rootCommand.AddCommand(githubCommand);
說明:
1、RootCommand是頂級命令,RootCommand可以添加Command,Command又可以再添加SubCommand。如此可以無限循環(huán),沒有限制 。但建議還是不要添加太多級的Command,調(diào)用的時候會不太友好
2、Command和RootCommand原理一樣,如果需要為Command添加Argument、Option和Command,可以參照前面的示例
7、調(diào)用解析
return rootCommand.InvokeAsync(args).Result;
8、調(diào)用示例
#執(zhí)行g(shù)ithub command crawler-line.exe github #執(zhí)行g(shù)ithub subcommand crawler-line.exe github sub #執(zhí)行argument option crawler-line.exe http://www.baidu.com -path "D:\test"
特別提示:
前面示例中,都是為RootCommand添加的Argument和Option,如果又指定 -path(Option),又執(zhí)行g(shù)ithub(Command)肯定會失敗。因為github這個命令是RootCommand的子命令,而-path選項是為RootCommand添加的
示例代碼
https://github.com/zhaotianff/Crawler-Line/tree/v1.0
以上就是C#命令行參數(shù)解析庫System.CommandLine介紹的詳細內(nèi)容,更多關(guān)于C#命令行參數(shù)解析庫System.CommandLine的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
C#事件標準命名規(guī)則及說明(包括用作事件類型的委托命名)
這篇文章主要介紹了C#事件標準命名規(guī)則及說明(包括用作事件類型的委托命名),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02insert語句太長用StringBuilder優(yōu)化一下
insert語句太長用StringBuilder優(yōu)化一下,下面是示例代碼,需要的朋友可以研究研究2014-07-07C#去除DataTable重復(fù)數(shù)據(jù)的三種方法
這篇文章主要介紹了C#去除DataTable重復(fù)數(shù)據(jù)的三種方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友們下面隨著小編來一起學(xué)習學(xué)習吧2021-02-02