최선의 방법은 분석 command line arguments,C#?[마감]
-
20-08-2019 - |
문제
건축할 때 콘솔는 응용 프로그램은 매개 변수를 사용할 수 있습니 인수로 전달하기 Main(string[] args)
.
과거에 나는 단순히 인덱스/루프는 편안하고 행 몇 가지 정규 표현식을 추출하는 값입니다.그러나,명령,더 복잡한 구문 분석 얻을 수 있습니다.
그래서 내가 관심이:
- 라이브러리를 사용하는
- 패턴을 사용하는
가정 명령어는 항상 준수하는 일반적인 과 같은 표준 여기에 응답.
해결책
나는 강력히 사용하는 것이 좋습니다 ndesk.options (선적 서류 비치) 및/또는 mono.options (동일한 API, 다른 네임 스페이스). an 문서의 예:
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# 개발을위한 가장 멋진 명령 줄 파서 중 하나가 함께 제공됩니다. 나는 그것을 조사하는 것이 좋습니다 API에 대한 Ivo Manolov의 블로그:
// 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);
모두가 자신의 애완 동물 명령 줄 파서를 가지고있는 것 같습니다.
이 도서관에는 a가 포함되어 있습니다 명령 줄 파서 명령 줄의 값으로 클래스를 초기화합니다. 그것은 수많은 기능을 가지고 있습니다 (나는 수년에 걸쳐 그것을 만들어 왔습니다).
로부터 선적 서류 비치...
Bizark 프레임 워크의 명령 줄 구문 분석에는 이러한 주요 기능이 있습니다.
- 자동 초기화 : 클래스 속성은 명령 줄 인수에 따라 자동으로 설정됩니다.
- 기본 속성 : 속성 이름을 지정하지 않고 값을 보내십시오.
- 가치 변환 : Bizark에 포함 된 강력한 ConverTex 클래스를 사용하여 값을 올바른 유형으로 변환합니다.
- 부울 깃발 : 플래그는 단순히 인수 (true 및 /b- fals의 경우 /b)를 사용하거나 true /false, yes /no 등을 추가하여 간단히 지정할 수 있습니다.
- 인수 배열 : 명령 줄 이름 뒤에 여러 값을 추가하여 배열로 정의 된 속성을 설정하십시오. 예, /x 1 2 3은 x를 배열 {1, 2, 3}로 채 웁니다 (x가 정수 배열로 정의된다고 가정).
- 명령 줄 별칭 : 속성은 여러 명령 줄 별칭을 지원할 수 있습니다. 예를 들어, 도움말은 별명을 사용합니까?.
- 부분 이름 인식 : 전체 이름이나 별명을 철자 할 필요는 없으며, 파서가 다른 사람의 속성/별명을 명확하게 표시 할 수있을 정도로 철자입니다.
- Clickonce 지원 : ClickOnce 배포 된 응용 프로그램의 URL에서 쿼리 문자열로 지정된 경우에도 속성을 초기화 할 수 있습니다. 명령 줄 초기화 메소드는 ClickOnce로 실행 중인지 여부를 감지하므로 코드를 사용할 때 코드를 변경할 필요가 없습니다.
- 자동으로 /? 돕다: 여기에는 콘솔의 너비를 고려하는 멋진 형식이 포함됩니다.
- 명령 줄 인수로드/저장 파일에 : 여러 번 실행하려는 여러 가지 크고 복잡한 명령 줄 인수 세트가있는 경우 특히 유용합니다.
나는 c# command line argument parser를 잠시 썼다. at : http://www.codeplex.com/commandlinearguments
박수 (Command Line Argument Parser)에는 사용 가능한 API가 있으며 훌륭하게 문서화되어 있습니다. 매개 변수에 주석을 달고 메소드를 만듭니다. https://github.com/adrianaisemberg/clap
이 문제에 대한 수많은 해결책이 있습니다. 완전성과 누군가가 원하는 경우 대안을 제공하기 위해 Google 코드 라이브러리.
첫 번째는 ArgumentList이며, 이는 명령 줄 매개 변수를 구문 분석 할 수 있습니다. 스위치 '/x : y'또는 '-x = y'로 정의 된 이름 값 쌍을 수집하고 '이름없는'항목 목록도 수집합니다. 기본입니다 사용법은 여기에서 설명합니다, 여기에서 수업을보십시오.
이것의 두 번째 부분은입니다 CommandInterpreter .NET 클래스에서 완전히 기능적 인 명령 줄 애플리케이션을 만듭니다. 예로서:
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 dosomething "문자열 값"5
-- 또는 --
program.exe dosomething /itivalue = 5- 값 : "문자열 값"
그것은 당신이 필요로하는 것만 큼 단순하거나 복잡합니다. 당신은 할 수 있습니다 소스 코드를 검토하십시오, 도움말을보십시오, 또는 이진을 다운로드하십시오.
좋아요 하나, 당신은 필요 여부에 대한 인수에 대해 "규칙을 정의"할 수 있기 때문에 ...
아니면 당신이 유닉스 사람이라면, 당신이 좋아할 수도 있습니다. gnu getopt .net 포트.
당신은 내 하나를 좋아할 수 있습니다 rug.cmd
사용하기 쉽고 확장 가능한 명령 줄 인수 파서. 핸들 : bool, plus / minus, 문자열, 문자열 목록, 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);
}
}
}
편집 : 이것은 내 프로젝트이며,이 답변은 제 3 자의 승인으로 간주되어서는 안됩니다. 그것은 내가 쓰는 모든 명령 줄 기반 프로그램에 그것을 사용한다고 말했습니다. 그것은 오픈 소스이며 다른 사람들이 그것으로부터 혜택을받을 수 있기를 희망합니다.
가 명령 라인에 인수에서 파서 http://www.codeplex.com/commonlibrarynet
할 수 있 인수 분석을 사용하여
1.특성
2.명시적으로 호출
3.단일 라인 여러 개의 인수 또는 문자 배열
그것은 처리할 수 있는 것들이 다음과 같습니다.
-config:Qa보:${오늘} -지역:'뉴욕'Settings01
그것은 사용하기 매우 쉽습니다.
이것은 내가 Novell을 기반으로 쓴 핸들러입니다. Options
수업.
이것은 while (input !="exit")
예를 들어 FTP 콘솔과 같은 대화식 콘솔 인 Style Loop.
예제 사용 :
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 Peter 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 Command Line Parsing 구현 구현을 발견했습니다.
- 사용하기 쉽습니다 - 문서를 찾을 수는 없지만 Fubucore 솔루션은 문서가 어떤 문서가 할 수있는 것보다 기능에 대해 더 많이 말하는 멋진 단위 테스트 세트를 포함하는 프로젝트를 제공합니다.
- 그것은 멋진 객체 지향 디자인, 코드 반복 또는 기타 명령 줄에 가지고 있던 다른 것들이 있습니다.
- 그것은 선언적입니다 : 당신은 기본적으로 명령과 매개 변수 세트에 대한 클래스를 작성하고 다양한 옵션을 설정하기 위해 속성으로 장식합니다 (예 : 이름, 설명, 필수/선택 사항).
- 라이브러리는 이러한 정의를 기반으로 멋진 사용법 그래프를 인쇄합니다.
아래는 이것을 사용하는 방법에 대한 간단한 예입니다. 사용법을 설명하기 위해 두 가지 명령이있는 간단한 유틸리티를 작성했습니다 .- 추가 (목록에 객체를 추가합니다 - 개체는 이름 (문자열), value (int) 및 부울 플래그로 구성됩니다 (목록) - 목록 현재 추가 된 모든 개체)
우선, 나는 'add'명령에 대한 명령 클래스를 썼습니다.
[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;
}
}
이 명령은 명령 인스턴스를 매개 변수로 사용하므로 다음을 정의합니다.
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;
}
}
'List'명령은 매개 변수를 사용하지 않으므로 NULLINPUT 클래스를 정의했습니다.
public class NullInput { }
지금 남은 것은 다음과 같이 Main () 메소드에서 이것을 연결하는 것입니다.
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
------------------------
그리고 'add'명령에 대한 샘플 사용량 :
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 CommandLets.
PowerShell에 의해 수행 된 구문 분석, CommandLets에 지정된 속성, 유효성 검사 지원, 매개 변수 세트, 파이프 라인, 오류보고, 도움말 및 기타 CommandLets에서 사용하기 위해 .NET 객체 중 최상의.
내가 시작하는 데 도움이 된 몇 가지 링크 :
C# cli 내가 쓴 매우 간단한 지휘관 인수 구문 분석 라이브러리입니다. 잘 문서화되고 오픈 소스입니다.
Genghis Command Line Parser 약간의 구식 일 수도 있지만, 그것은 매우 기능이 완벽하며 나에게 아주 잘 작동합니다.
오픈 소스 라이브러리를 제안합니다 CSHARPOPTPARSE. 명령 줄을 구문 분석하고 명령 줄 입력으로 사용자 정의 .NET 객체를 수화시킵니다. C# 콘솔 응용 프로그램을 작성할 때는 항상이 라이브러리로 돌아갑니다.
Apache Commons Cli API의 .NET 포트를 사용하십시오. 이것은 훌륭합니다.
http://sourceforge.net/projects/dotnetcli/
개념과 소개를위한 원래 API
기본 인수를 지원하는 명령 줄 구문 분석에 매우 간단한 사용하기 쉬운 임시 클래스.
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"));
}
}