我目前正在开发一个需要解析命令行参数的项目。到目前为止,我一直在关注this tutorial,这非常有帮助,但我无法弄清楚如何在参数中返回变量(--author = example)。我也无法弄清楚为什么 parse [] = getContents
会导致错误(我必须取消注释)。
这是我的代码:
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)
答案 0 :(得分:3)
跟进@ ThomasM.DuBuisson评论optparse-applicative是一个很棒的cli和参数解析包。还有另一个包optparse-simple,它建立在前一个包之上,并且有一些辅助工具可以简化一些事情。
这样您可以开始使用optparse-applicative
这是您的示例的实现:
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
来自GHCi的用法示例:
λ> :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