2017-12-06 1 views
0

현재 명령 줄 인수를 구문 분석해야하는 프로젝트에서 작업 중입니다. 지금까지 나는 매우 도움이되어 this tutorial을 따라 왔지만 인수에서 변수 (--author = example)를 반환하는 방법을 알 수 없습니다. 나는 또한 왜 parse [] = getContents이 원인인지 알아낼 수 없다. (주석 처리하지 않으면 안된다.) 코멘트 optparse-applicative은 CLI 및 인수를 구문 분석에 대한 좋은 패키지가 ThomasM.DuBuisson하스켈에서 명령 줄 인수 구문 분석

module Main where 

import qualified System.Environment as SE 
import qualified System.Exit as E 
import qualified Lib as Lib 

main = do 
    args <- SE.getArgs 
    rem <- parse args 
    Lib.someFunc 
    putStrLn rem 
    putStrLn "Hello" 

tac = unlines . reverse . lines 

parse ["--help"] = usage >> exit 
parse ["--version"] = version >> exit 
parse ["--author=xyz"] = return "xyz" 
-- parse ["--author=?"] = ? 
{- 
this is the code I am trying to figure out... how do I get parse the passed in variable name? 
-} 

-- parse []   = getContents 
{- 
the above line generates this error when I run 'main' in GHCi: 

    *Main> <stdin>: hIsEOF: illegal operation (handle is semi-closed) 
    Process intero exited abnormally with code 1 

-} 
parse fs   = concat `fmap` mapM readFile fs 

usage = putStrLn "Usage: gc2" 
version = putStrLn "gc2 -- git-cal in Haskell2010 - 0.1" 
exit = E.exitWith E.ExitSuccess 
die  = E.exitWith (E.ExitFailure 1) 
+1

'getContents'는 모든 입력을 가져, 그리고해야 당신이 여기 optparse-applicative 시작할 수 너무

는 예를 구현 한 것입니다 그 후에는 입력 내용을 읽지 않습니다. 그 계약을 만족시키는거야? 예를 들어'Lib.someFunc'을 확인하십시오. – chi

+0

감사합니다. (Lib.someFunc에서 System.Process를 사용했기 때문에 오류가있는 것 같습니다.) – kuwze

+1

거기에는 인수 파싱 라이브러리가 있습니다. 그 중 하나를 사용하지 않을 이유가 있습니까? –

답변

3

@ 후속하려면 :

여기 내 코드입니다. 이전 패키지 위에 빌드 된 또 다른 패키지 optparse-simple이 있고 약간을 단순화하는 몇 가지 도우미가 있습니다. GHCi에서

data Options = Options 
    { author :: String 
    } 

main :: IO() 
main = do 
    let ver = "gc2 -- git-cal in Haskell2010 - 0.1" 
    args <- 
    execParser $ 
    info 
     (Options <$> 
     strOption (long "author" <> 
        short 'a' <> 
        help "Name of the author.") <* 
     infoOption ver (long "version" <> 
         short 'v' <> 
         help "Display version and exit.") <* 
     abortOption ShowHelpText (long "help" <> 
           short 'h' <> 
           help "Display this message.")) 
     (progDesc "Very powerful tool." <> fullDesc) 
    putStrLn $ author args 

및 사용 예 :

λ> :main 
Missing: (-a|--author ARG) 

Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help] 
    Very powerful tool. 
*** Exception: ExitFailure 1 
λ> :main --version 
gc2 -- git-cal in Haskell2010 - 0.1 
*** Exception: ExitSuccess 
λ> :main --help 
Usage: <interactive> (-a|--author ARG) [-v|--version] [-h|--help] 
    Very powerful tool. 

Available options: 
    -a,--author ARG   Name of the author. 
    -v,--version    Display version and exit. 
    -h,--help    Display this message. 
*** Exception: ExitSuccess 
λ> :main --author Me 
Me