[macos] Swift에서 명령 줄 인수에 어떻게 액세스합니까?

Swift에서 명령 줄 응용 프로그램의 명령 줄 인수에 어떻게 액세스합니까?



답변

Apple ArgumentParser은이를 위해 라이브러리를 출시했습니다 .

ArgumentParser간단하고 즐겁게 사용할 수있는 새로운 오픈 소스 라이브러리 인 을 발표하게되어 기쁩니다 ! — Swift에서 명령 줄 인수를 구문 분석합니다.

https://swift.org/blog/argument-parser/


신속한 인수 파서

https://github.com/apple/swift-argument-parser

명령 줄에서 수집해야하는 정보를 정의하는 유형을 선언하여 시작합니다. ArgumentParser의 속성 래퍼 중 하나를 사용하여 저장된 각 속성을 장식 하고 ParsableCommand.

ArgumentParser라이브러리는 명령 줄 인수를 구문 분석 명령 유형을 인스턴스화 한 다음 중 하나를 사용자 정의 실행 run()유용한 메시지와 함께 방법 또는 종료.


답변

업데이트 01/17/17 : Swift 3의 예제가 업데이트 Process되었습니다 CommandLine.


업데이트 09/30/2015 : Swift 2에서 작동하도록 예제를 업데이트했습니다.


실제로 Foundation 또는 C_ARGVC_ARGC.

Swift 표준 라이브러리에는 라는 CommandLine컬렉션이있는 구조체 가 포함되어 있습니다 . 따라서 다음과 같은 인수를 전환 할 수 있습니다.Stringarguments

for argument in CommandLine.arguments {
    switch argument {
    case "arg1":
        print("first argument")

    case "arg2":
        print("second argument")

    default:
        print("an argument")
    }
}


답변

Swift 3에서는 CommandLine대신 enum을 사용하십시오.Process

그래서:

let arguments = CommandLine.arguments


답변

최상위 상수 C_ARGCC_ARGV.

for i in 1..C_ARGC {
    let index = Int(i);

    let arg = String.fromCString(C_ARGV[index])
    switch arg {
    case "this":
        println("this yo");

    case "that":
        println("that yo")

    default:
        println("dunno bro")
    }
}

“배열” 1..C_ARGC의 첫 번째 요소 C_ARGV가 응용 프로그램의 경로 이기 때문에 범위를 사용하고 있습니다 .

C_ARGV변수 실제로 배열되지 않지만, 서브 스크립트 배열 같다.


답변

이전 “getopt”(Swift에서 사용 가능)를 사용하려는 사람은 누구나 이것을 참조로 사용할 수 있습니다. C에서 GNU 예제의 Swift 포트를 만들었습니다.

http://www.gnu.org/software/libc/manual/html_node/Example-of-Getopt.html

전체 설명과 함께. 테스트를 거쳐 완벽하게 작동합니다. 재단도 필요하지 않습니다.

var aFlag   = 0
var bFlag   = 0
var cValue  = String()

let pattern = "abc:"
var buffer = Array(pattern.utf8).map { Int8($0) }

while  true {
    let option = Int(getopt(C_ARGC, C_ARGV, buffer))
    if option == -1 {
        break
    }
    switch "\(UnicodeScalar(option))"
    {
    case "a":
        aFlag = 1
        println("Option -a")
    case "b":
        bFlag = 1
        println("Option -b")
    case "c":
        cValue = String.fromCString(optarg)!
        println("Option -c \(cValue)")
    case "?":
        let charOption = "\(UnicodeScalar(Int(optopt)))"
        if charOption == "c" {
            println("Option '\(charOption)' requires an argument.")
        } else {
            println("Unknown option '\(charOption)'.")
        }
        exit(1)
    default:
        abort()
    }
}
println("aflag ='\(aFlag)', bflag = '\(bFlag)' cvalue = '\(cValue)'")

for index in optind..<C_ARGC {
    println("Non-option argument '\(String.fromCString(C_ARGV[Int(index)])!)'")
}


답변

CommandLine.arguments배열 을 사용하여 인수 파서를 만들고 원하는 논리를 추가 할 수 있습니다.

테스트 할 수 있습니다. 파일 생성arguments.swift

//Remember the first argument is the name of the executable
print("you passed \(CommandLine.arguments.count - 1) argument(s)")
print("And they are")
for argument in CommandLine.arguments {
    print(argument)
}

컴파일하고 실행하십시오.

$ swiftc arguments.swift
$ ./arguments argument1 argument2 argument3

자체 인수 구문 분석기를 작성하는 데있어 문제는 모든 명령 줄 인수 규칙을 고려하는 것입니다. 기존 Argument Parser를 사용하는 것이 좋습니다.

다음을 사용할 수 있습니다.

  • Vapor의 콘솔 모듈
  • Swift Package 관리자가 사용하는 TSCUtility Argument Parser
  • Apple에서 오픈 소스로 제공하는 Swift Argument Parser

세 가지 모두에서 명령 줄 도구를 빌드하는 방법에 대해 작성했습니다. 당신은 그것들을 확인하고 당신에게 가장 적합한 스타일을 결정해야합니다.

관심이 있다면 여기에 링크가 있습니다.


답변