最好的方式来分析命令行的论点在C#?[关闭]
-
20-08-2019 - |
题
当建立控制台应用程序参数,可以利用的论点过来 Main(string[] args)
.
在过去我已经简单地编制索引/环阵列,并完成一些常规表述中提取价值观。然而,当命令变得更加复杂,分析可获得很丑陋.
所以我很有兴趣:
- 库使用
- 模式,你使用
假设的命令始终坚持的共同标准,例如 在这里找到答案.
解决方案
我强烈建议您使用 NDesk.选项 (文档)和/或 单。选项 (同样的API,不同的名字空间).一个 例从文件:
bool show_help = false;
List<string> names = new List<string> ();
int repeat = 1;
var p = new OptionSet () {
{ "n|name=", "the {NAME} of someone to greet.",
v => names.Add (v) },
{ "r|repeat=",
"the number of {TIMES} to repeat the greeting.\n" +
"this must be an integer.",
(int v) => repeat = v },
{ "v", "increase debug message verbosity",
v => { if (v != null) ++verbosity; } },
{ "h|help", "show this message and exit",
v => show_help = v != null },
};
List<string> extra;
try {
extra = p.Parse (args);
}
catch (OptionException e) {
Console.Write ("greet: ");
Console.WriteLine (e.Message);
Console.WriteLine ("Try `greet --help' for more information.");
return;
}
其他提示
我真的很喜欢命令行分析器库( http://commandline.codeplex.com/ ).它有一个非常简单和优雅的方式设立的参数通过的属性:
class Options
{
[Option("i", "input", Required = true, HelpText = "Input file to read.")]
public string InputFile { get; set; }
[Option(null, "length", HelpText = "The maximum number of bytes to process.")]
public int MaximumLenght { get; set; }
[Option("v", null, HelpText = "Print details during execution.")]
public bool Verbose { get; set; }
[HelpOption(HelpText = "Display this help screen.")]
public string GetUsage()
{
var usage = new StringBuilder();
usage.AppendLine("Quickstart Application 1.0");
usage.AppendLine("Read user manual for usage instructions...");
return usage.ToString();
}
}
的 WPF TestApi库 带有一个最好的命令行分析程序用于C#发展。我强烈推荐找到它,从 伊沃*Manolov的博客上API:
// EXAMPLE #2:
// Sample for parsing the following command-line:
// Test.exe /verbose /runId=10
// This sample declares a class in which the strongly-
// typed arguments are populated
public class CommandLineArguments
{
bool? Verbose { get; set; }
int? RunId { get; set; }
}
CommandLineArguments a = new CommandLineArguments();
CommandLineParser.ParseArguments(args, a);
看起来像每个人都有自己的宠物的命令行的分析程序,图我有更好的增加排雷以及:).
该库包含一个 命令行分析器 这将初始化一类的价值从命令行。它有一吨的特点(我已经建立起来过多年)。
从 文档...
命令行分析在BizArk框架这些关键特点:
- 自动初始化: 类性质是自动设定根据命令行参数。
- 默认的性质: 发送一个价值没有指定酒店的名字。
- 值转换: 使用强大的ConvertEx类还包括在BizArk转换值为合适的类型。
- Boolean标志: 标志可以规定,通过简单的使用的说法(ex/b为真正的和/b假)或通过增加价值true/false,是的/不,等等。
- 参阵列: 简单地添加个数值之后,命令行名称设置一个属性,是定义为一个阵列。Ex/x1 2 3将填充x与阵{1,2,3}(假设x被定义为一系列整数)。
- 命令行的别名: 一个酒店可以支持多种命令行的别名。例如,帮助使用的别名?.
- 部分名称识别: 你不需要拼写出完整的姓名或别名,只是拼写足够的分析器来消除性/别名其他人。
- 支持ClickOnce: 可以初始化特性甚至当他们被指定为查询串在一URL ClickOnce部署的应用。该命令行初始化的方法将检测,如果它运行为ClickOnce或不那么你的代码不需要改变时,使用它。
- 将自动创建/?帮助: 这包括好的格式,考虑到宽慰的。
- 装载/节省的命令行参数的文件: 这是特别有用的,如果你有多大型、复杂的命令行的论点,你要运行多次。
我写了一C#命令行参数分析器。其: http://www.codeplex.com/CommandLineArguments
拍手 (command line argument parser)具有一个可用API和奇妙的是记录在案。你做的方法,注释的参数。 https://github.com/adrianaisemberg/CLAP
有很多办法解决这一问题。为了完整性和提供的选择,如果一个人的欲望我加入这个答案对两个有用的类在我的 谷歌码图书馆.
第一是参数列表,它只负责分析命令行参数。它收集名称值对的定义的交换机/x:y'或'-x=y',也收集一个列表中的'未命名的'项目。它的基础 使用的是讨论在这里, 看类在这里.
第二部分的这是的 CommandInterpreter 它创建了一个功能齐全的命令行程序出你的.净类。作为一个例子:
using CSharpTest.Net.Commands;
static class Program
{
static void Main(string[] args)
{
new CommandInterpreter(new Commands()).Run(args);
}
//example ‘Commands’ class:
class Commands
{
public int SomeValue { get; set; }
public void DoSomething(string svalue, int ivalue)
{ ... }
与上述实例中的代码可以运行以下:
Program.exe 或重写现有的"串值"5
-或者--
Program.exe 或重写现有/ivalue=5-svalue:"串值"
我喜欢 那一个, 因为你可以"定义的规则"的论点,根据需要或不...
或如果你是一个Unix家伙,你可能会喜欢的 GNU Getopt.净 港口。
你可能会喜欢我一个 地毯。Cmd
容易使用和可膨胀的命令行参数的分析器。把手:Bool,再加上/减去、串串名单,CSV枚举。
建立在'/?助模式。
建立在'/??' 和'/?D'的文件的发生器模式。
static void Main(string[] args)
{
// create the argument parser
ArgumentParser parser = new ArgumentParser("ArgumentExample", "Example of argument parsing");
// create the argument for a string
StringArgument StringArg = new StringArgument("String", "Example string argument", "This argument demonstrates string arguments");
// add the argument to the parser
parser.Add("/", "String", StringArg);
// parse arguemnts
parser.Parse(args);
// did the parser detect a /? argument
if (parser.HelpMode == false)
{
// was the string argument defined
if (StringArg.Defined == true)
{
// write its value
RC.WriteLine("String argument was defined");
RC.WriteLine(StringArg.Value);
}
}
}
编辑:这是我的项目和作为这样这个答案不应被看作是一种认可,从一个第三方。说我使用它,用于每一个基于命令行程序是我写的,它是开放源代码和我希望,其他人可能从中受益。
有一个命令行参数分析器在 http://www.codeplex.com/commonlibrarynet
它可以分析参数的使用
1.属性
2.明确呼吁
3.单线的多种参数或串阵列
它可以处理事情如下:
-config:Qastartdate:${今天} -区域:'纽约Settings01
这是非常容易使用。
这是一个处理程序是我写的基础上Novell Options
类。
这一旨在控制台应用程序的执行 while (input !="exit")
风格的循环,一个互动的控制台,如FTP控制台的例子。
例的使用情况:
static void Main(string[] args)
{
// Setup
CommandHandler handler = new CommandHandler();
CommandOptions options = new CommandOptions();
// Add some commands. Use the v syntax for passing arguments
options.Add("show", handler.Show)
.Add("connect", v => handler.Connect(v))
.Add("dir", handler.Dir);
// Read lines
System.Console.Write(">");
string input = System.Console.ReadLine();
while (input != "quit" && input != "exit")
{
if (input == "cls" || input == "clear")
{
System.Console.Clear();
}
else
{
if (!string.IsNullOrEmpty(input))
{
if (options.Parse(input))
{
System.Console.WriteLine(handler.OutputMessage);
}
else
{
System.Console.WriteLine("I didn't understand that command");
}
}
}
System.Console.Write(">");
input = System.Console.ReadLine();
}
}
和来源:
/// <summary>
/// A class for parsing commands inside a tool. Based on Novell Options class (http://www.ndesk.org/Options).
/// </summary>
public class CommandOptions
{
private Dictionary<string, Action<string[]>> _actions;
private Dictionary<string, Action> _actionsNoParams;
/// <summary>
/// Initializes a new instance of the <see cref="CommandOptions"/> class.
/// </summary>
public CommandOptions()
{
_actions = new Dictionary<string, Action<string[]>>();
_actionsNoParams = new Dictionary<string, Action>();
}
/// <summary>
/// Adds a command option and an action to perform when the command is found.
/// </summary>
/// <param name="name">The name of the command.</param>
/// <param name="action">An action delegate</param>
/// <returns>The current CommandOptions instance.</returns>
public CommandOptions Add(string name, Action action)
{
_actionsNoParams.Add(name, action);
return this;
}
/// <summary>
/// Adds a command option and an action (with parameter) to perform when the command is found.
/// </summary>
/// <param name="name">The name of the command.</param>
/// <param name="action">An action delegate that has one parameter - string[] args.</param>
/// <returns>The current CommandOptions instance.</returns>
public CommandOptions Add(string name, Action<string[]> action)
{
_actions.Add(name, action);
return this;
}
/// <summary>
/// Parses the text command and calls any actions associated with the command.
/// </summary>
/// <param name="command">The text command, e.g "show databases"</param>
public bool Parse(string command)
{
if (command.IndexOf(" ") == -1)
{
// No params
foreach (string key in _actionsNoParams.Keys)
{
if (command == key)
{
_actionsNoParams[key].Invoke();
return true;
}
}
}
else
{
// Params
foreach (string key in _actions.Keys)
{
if (command.StartsWith(key) && command.Length > key.Length)
{
string options = command.Substring(key.Length);
options = options.Trim();
string[] parts = options.Split(' ');
_actions[key].Invoke(parts);
return true;
}
}
}
return false;
}
}
我个人最喜欢的是 http://www.codeproject.com/KB/recipes/plossum_commandline.aspx 由彼得*Palotas:
[CommandLineManager(ApplicationName="Hello World",
Copyright="Copyright (c) Peter Palotas")]
class Options
{
[CommandLineOption(Description="Displays this help text")]
public bool Help = false;
[CommandLineOption(Description = "Specifies the input file", MinOccurs=1)]
public string Name
{
get { return mName; }
set
{
if (String.IsNullOrEmpty(value))
throw new InvalidOptionValueException(
"The name must not be empty", false);
mName = value;
}
}
private string mName;
}
我最近遇到了FubuCore命令行分析执行我真的很喜欢它,原因是:
- 这是易于使用的-尽管我没能找到一个文件,FubuCore解决方案还提供了一个项目含有一个很好的设置单元的测试,说更多的有关功能比任何文件可以
- 它有一个很好的对象为导向的设计,没有代码重复或其他类似的东西我有我的命令行分析应用程序
- 它的声明:你基本上写类命令和成套参数和装饰他们的属性设置的各种选择(例如名字,说明,强制性/可选)
- 图书馆即使是打印一个很好的使用情况图,根据这些定义
以下是一个简单的例子如何使用这个。为了说明的使用情况,我已经写了一个简单的工具,有两个的命令:-添加(增加了一个目的列表的对象包括一个名字(string)、价值(int)和布尔标志) -列表(列出所有的目前添加的对象)
首先,我写了一命令的类"添加"命令:
[Usage("add", "Adds an object to the list")]
[CommandDescription("Add object", Name = "add")]
public class AddCommand : FubuCommand<CommandInput>
{
public override bool Execute(CommandInput input)
{
State.Objects.Add(input); // add the new object to an in-memory collection
return true;
}
}
这种命令需要CommandInput实例作为参数,所以我定义,下一步:
public class CommandInput
{
[RequiredUsage("add"), Description("The name of the object to add")]
public string ObjectName { get; set; }
[ValidUsage("add")]
[Description("The value of the object to add")]
public int ObjectValue { get; set; }
[Description("Multiply the value by -1")]
[ValidUsage("add")]
[FlagAlias("nv")]
public bool NegateValueFlag { get; set; }
}
下一个命令是"列表",这是实施如下:
[Usage("list", "List the objects we have so far")]
[CommandDescription("List objects", Name = "list")]
public class ListCommand : FubuCommand<NullInput>
{
public override bool Execute(NullInput input)
{
State.Objects.ForEach(Console.WriteLine);
return false;
}
}
该名单'的命令没有参数,所以我定义的一个NullInput类:
public class NullInput { }
现在是线此在主要()方法,像这样:
static void Main(string[] args)
{
var factory = new CommandFactory();
factory.RegisterCommands(typeof(Program).Assembly);
var executor = new CommandExecutor(factory);
executor.Execute(args);
}
该程序作为预期的、印刷的提示关于正确使用在任何情况下命令是无效:
------------------------
Available commands:
------------------------
add -> Add object
list -> List objects
------------------------
和一个样品使用的"添加"命令:
Usages for 'add' (Add object)
add <objectname> [-nv]
-------------------------------------------------
Arguments
-------------------------------------------------
objectname -> The name of the object to add
objectvalue -> The value of the object to add
-------------------------------------------------
-------------------------------------
Flags
-------------------------------------
[-nv] -> Multiply the value by -1
-------------------------------------
Powershell Commandlet。
分析通过powershell的基础上指定的属性的commandlet,支持验证、参数设置、管道传输错误的报告、帮助,最重要的是所有返回。净的对象,使用在其他commandlet。
几个链接我找到了有用的开始:
C#CLI 是一个非常简单的命令行参数分析图书馆的,我写了。它是好的-记录和公开来源。
成吉思汗的命令行分析器 可能会有点过时了,但这是非常功能的完整和工作得很好,对我来说。
我建议开放源图书馆 CSharpOptParse.它分析的命令线路和水用户的定义。净物体的命令行输入。我总是变成这个图书馆的时候写的C#控制台应用程序。
一个非常简单的易于使用的特别类命令行分析,支持缺省参数。
class CommandLineArgs
{
public static CommandLineArgs I
{
get
{
return m_instance;
}
}
public string argAsString( string argName )
{
if (m_args.ContainsKey(argName)) {
return m_args[argName];
}
else return "";
}
public long argAsLong(string argName)
{
if (m_args.ContainsKey(argName))
{
return Convert.ToInt64(m_args[argName]);
}
else return 0;
}
public double argAsDouble(string argName)
{
if (m_args.ContainsKey(argName))
{
return Convert.ToDouble(m_args[argName]);
}
else return 0;
}
public void parseArgs(string[] args, string defaultArgs )
{
m_args = new Dictionary<string, string>();
parseDefaults(defaultArgs );
foreach (string arg in args)
{
string[] words = arg.Split('=');
m_args[words[0]] = words[1];
}
}
private void parseDefaults(string defaultArgs )
{
if ( defaultArgs == "" ) return;
string[] args = defaultArgs.Split(';');
foreach (string arg in args)
{
string[] words = arg.Split('=');
m_args[words[0]] = words[1];
}
}
private Dictionary<string, string> m_args = null;
static readonly CommandLineArgs m_instance = new CommandLineArgs();
}
class Program
{
static void Main(string[] args)
{
CommandLineArgs.I.parseArgs(args, "myStringArg=defaultVal;someLong=12");
Console.WriteLine("Arg myStringArg : '{0}' ", CommandLineArgs.I.argAsString("myStringArg"));
Console.WriteLine("Arg someLong : '{0}' ", CommandLineArgs.I.argAsLong("someLong"));
}
}