다음을 통해 공유


System.CommandLine 명령, 옵션 및 인수를 정의하는 방법

Important

System.CommandLine은(는) 현재 미리 보기로 제공되며 이 설명서는 버전 2.0 베타 4용입니다. 일부 정보는 릴리스되기 전에 상당 부분 수정될 수 있는 시험판 제품과 관련이 있습니다. Microsoft는 여기에 제공된 정보에 대해 어떠한 명시적이거나 묵시적인 보증도 하지 않습니다.

이 문서에서는 System.CommandLine라이브러리로 빌드된 명령줄 앱에서 명령, 옵션인수를 정의하는 방법을 설명합니다. 이러한 기술을 보여 주는 전체 애플리케이션을 빌드하려면 시작하기System.CommandLine 자습서를 참조하세요.

명령줄 앱의 명령, 옵션 및 인수를 디자인하는 방법에 대한 지침은 디자인 지침을 참조하세요.

루트 명령 정의

모든 명령줄 앱에는 실행 파일 자체를 참조하는 루트 명령이 있습니다. 하위 명령, 옵션 또는 인수가 없는 앱이 있는 경우 코드를 호출하는 가장 간단한 사례는 다음과 같습니다.

using System.CommandLine;

class Program
{
    static async Task Main(string[] args)
    {
        var rootCommand = new RootCommand("Sample command-line app");

        rootCommand.SetHandler(() =>
        {
            Console.WriteLine("Hello world!");
        });

        await rootCommand.InvokeAsync(args);
    }
}

하위 명령 정의

명령에는 하위 명령 또는 동사, 하위 명령으로 알려진 자식 명령이 있을 수 있으며 필요한 만큼 중첩할 수 있습니다. 다음 예제와 같이 하위 명령을 추가할 수 있습니다.

var rootCommand = new RootCommand();
var sub1Command = new Command("sub1", "First-level subcommand");
rootCommand.Add(sub1Command);
var sub1aCommand = new Command("sub1a", "Second level subcommand");
sub1Command.Add(sub1aCommand);

이 예제의 가장 안쪽 하위 명령은 다음과 같이 호출할 수 있습니다.

myapp sub1 sub1a

옵션 정의

명령 처리기 메서드에는 일반적으로 매개 변수가 있으며, 값은 명령줄 옵션에서 가져올 수 있습니다. 다음 예제에서는 두 가지 옵션을 만들고 루트 명령에 추가합니다. 옵션 이름에는 POSIX CLIs로는 일반적인 이중 하이픈 접두사를 포함합니다. 명령 처리기 코드는 이러한 옵션의 값을 표시합니다.

var delayOption = new Option<int>
    (name: "--delay",
    description: "An option whose argument is parsed as an int.",
    getDefaultValue: () => 42);
var messageOption = new Option<string>
    ("--message", "An option whose argument is parsed as a string.");

var rootCommand = new RootCommand();
rootCommand.Add(delayOption);
rootCommand.Add(messageOption);

rootCommand.SetHandler((delayOptionValue, messageOptionValue) =>
    {
        Console.WriteLine($"--delay = {delayOptionValue}");
        Console.WriteLine($"--message = {messageOptionValue}");
    },
    delayOption, messageOption);

다음은 명령줄 입력 및 이전 예제 코드에 대한 결과 출력의 예입니다.

myapp --delay 21 --message "Hello world!"
--delay = 21
--message = Hello world!

글로벌 옵션

한 번에 하나의 명령에 옵션을 추가하려면 앞의 예제와 같이 Add 또는 AddOption 메서드를 사용합니다. 명령에 옵션을 추가하고 모든 하위 명령에 재귀적으로 추가하려면 다음 예제와 같이 AddGlobalOption 메서드를 사용합니다.

var delayOption = new Option<int>
    ("--delay", "An option whose argument is parsed as an int.");
var messageOption = new Option<string>
    ("--message", "An option whose argument is parsed as a string.");

var rootCommand = new RootCommand();
rootCommand.AddGlobalOption(delayOption);
rootCommand.Add(messageOption);

var subCommand1 = new Command("sub1", "First level subcommand");
rootCommand.Add(subCommand1);

var subCommand1a = new Command("sub1a", "Second level subcommand");
subCommand1.Add(subCommand1a);

subCommand1a.SetHandler((delayOptionValue) =>
    {
        Console.WriteLine($"--delay = {delayOptionValue}");
    },
    delayOption);

await rootCommand.InvokeAsync(args);

위의 코드는 루트 명령에 전역 옵션으로 --delay을(를) 추가하고 subCommand1a 처리기에서 사용할 수 있습니다.

인수 정의

인수 정의되고 옵션과 같은 명령에 추가됩니다. 다음 예제는 옵션 예제와 비슷하지만 옵션 대신 인수를 정의합니다.

var delayArgument = new Argument<int>
    (name: "delay",
    description: "An argument that is parsed as an int.",
    getDefaultValue: () => 42);
var messageArgument = new Argument<string>
    ("message", "An argument that is parsed as a string.");

var rootCommand = new RootCommand();
rootCommand.Add(delayArgument);
rootCommand.Add(messageArgument);

rootCommand.SetHandler((delayArgumentValue, messageArgumentValue) =>
    {
        Console.WriteLine($"<delay> argument = {delayArgumentValue}");
        Console.WriteLine($"<message> argument = {messageArgumentValue}");
    },
    delayArgument, messageArgument);

await rootCommand.InvokeAsync(args);

다음은 명령줄 입력 및 이전 예제 코드에 대한 결과 출력의 예입니다.

myapp 42 "Hello world!"
<delay> argument = 42
<message> argument = Hello world!

앞의 예제에서 messageArgument 같은 기본값 없이 정의된 인수는 필수 인수로 처리됩니다. 필요한 인수가 제공되지 않으면 오류 메시지가 표시되고 명령 처리기가 호출되지 않습니다.

별칭 정의

명령과 옵션 모두 별칭을 지원합니다. AddAlias호출하여 옵션에 별칭을 추가할 수 있습니다.

var option = new Option("--framework");
option.AddAlias("-f");

이 별칭을 사용할 경우 다음 명령줄은 동일합니다.

myapp -f net6.0
myapp --framework net6.0

명령 별칭은 동일한 방식으로 작동합니다.

var command = new Command("serialize");
command.AddAlias("serialise");

이 코드는 다음 명령줄을 동등하게 만듭니다.

myapp serialize
myapp serialise

정의하는 옵션 별칭의 수를 최소화하고 특정 별칭을 정의하지 않는 것이 좋습니다. 자세한 내용은 약식 별칭을 참조하세요.

필수 옵션

필요한 옵션을 만들려면 다음 예제와 같이 IsRequired 속성을 true(으)로 설정합니다.

var endpointOption = new Option<Uri>("--endpoint") { IsRequired = true };
var command = new RootCommand();
command.Add(endpointOption);

command.SetHandler((uri) =>
    {
        Console.WriteLine(uri?.GetType());
        Console.WriteLine(uri?.ToString());
    },
    endpointOption);

await command.InvokeAsync(args);

명령 도움말의 옵션 섹션은 옵션이 필수임을 나타냅니다.

Options:
  --endpoint <uri> (REQUIRED)
  --version               Show version information
  -?, -h, --help          Show help and usage information

이 예제 앱의 명령줄에 --endpoint이(가) 포함되어 있지 않으면 오류 메시지가 표시되고 명령 처리기가 호출되지 않습니다.

Option '--endpoint' is required.

필수 옵션에 기본값이 있는 경우 명령줄에 옵션을 지정할 필요가 없습니다. 이 경우 기본값은 필요한 옵션 값을 제공합니다.

숨겨진 명령, 옵션 및 인수

명령, 옵션 또는 인수를 지원하지만 쉽게 검색할 수는 없습니다. 예를 들어 더 이상 사용되지 않거나 관리 또는 미리 보기 기능일 수 있습니다. 다음 예제와 같이 IsHidden 속성을 사용하여 탭 완성 또는 도움말을 사용하여 사용자가 이러한 기능을 검색하지 못하도록 합니다.

var endpointOption = new Option<Uri>("--endpoint") { IsHidden = true };
var command = new RootCommand();
command.Add(endpointOption);

command.SetHandler((uri) =>
    {
        Console.WriteLine(uri?.GetType());
        Console.WriteLine(uri?.ToString());
    },
    endpointOption);

await command.InvokeAsync(args);

이 예제 명령의 옵션 섹션은 --endpoint 옵션을 생략하는 데 도움이 됩니다.

Options:
  --version               Show version information
  -?, -h, --help          Show help and usage information

인수 arity 설정

Arity 속성을 사용하여 인수arity를 명시적으로 설정할 수 있지만 대부분의 경우 필요하지 않습니다. System.CommandLine 인수 형식에 따라 인수 아성을 자동으로 결정합니다.

인수 형식 기본 arity
Boolean ArgumentArity.ZeroOrOne
컬렉션 형식 ArgumentArity.ZeroOrMore
기타 등등 ArgumentArity.ExactlyOne

다중 인수

기본적으로 명령을 호출할 때 옵션 이름을 반복하여 1보다 큰 최대 arity 옵션에 대해 여러 인수를 지정할 수 있습니다.

myapp --items one --items two --items three

옵션 이름을 반복하지 않고 여러 인수를 허용하려면 Option.AllowMultipleArgumentsPerToken을(를) true(으)로 설정합니다. 이 설정을 사용하면 다음 명령줄을 입력할 수 있습니다.

myapp --items one two three

최대 인수 크기가 1인 경우 동일한 설정에 다른 효과가 있습니다. 옵션을 반복할 수 있지만 줄의 마지막 값만 사용합니다. 다음 예제에서는 three 값이 앱에 전달됩니다.

myapp --item one --item two --item three

유효한 인수 값 나열

옵션 또는 인수에 유효한 값 목록을 지정하려면 다음 예제와 같이 열거형을 옵션 형식으로 지정하거나 FromAmong을(를) 사용합니다.

var languageOption = new Option<string>(
    "--language",
    "An option that that must be one of the values of a static list.")
        .FromAmong(
            "csharp",
            "fsharp",
            "vb",
            "pwsh",
            "sql");

다음은 명령줄 입력 및 이전 예제 코드에 대한 결과 출력의 예입니다.

myapp --language not-a-language
Argument 'not-a-language' not recognized. Must be one of:
        'csharp'
        'fsharp'
        'vb'
        'pwsh'
        'sql'

명령 도움말의 옵션 섹션에는 유효한 값이 표시됩니다.

Options:
  --language <csharp|fsharp|vb|pwsh|sql>  An option that must be one of the values of a static list.
  --version                               Show version information
  -?, -h, --help                          Show help and usage information

옵션 및 인수 유효성 검사

인수 유효성 검사 및 사용자 지정 방법에 대한 자세한 내용은 매개 변수 바인딩 문서의 다음 섹션을 참조하세요.

참고 항목