我使用的是optparse-applicative版本0.7.0.2。
我想要编写一个解析器,它接受一些强制选项,但是在没有选项的情况下调用时,它同时显示了使用和帮助,而不仅仅是使用(也就是说,我希望没有选项的调用与--help一起作为调用)。
我不知道怎么做,即使文件说这是可能的:
本例中的hello选项是强制性的(因为它没有默认值),因此运行不带任何参数的程序将显示帮助文本
有这样的例子吗?主文档中的一个对我不起作用(它只打印用法)。
发布于 2013-11-24 12:45:20
目前,要做到这一点,唯一的方法是从customExecParser中创建您自己的Options.Applicative.Extra模块版本。有悬而未决的问题使这更简单。
像这样的东西应该非常接近你要找的东西:
import Options.Applicative
import Options.Applicative.Help as AH
import Options.Applicative.Types as AT
import System.Environment (getArgs, getProgName)
import System.Exit (exitWith, ExitCode(..))
import System.IO (hPutStr, stderr)
execParserWithHelp :: ParserPrefs -> ParserInfo a -> IO a
execParserWithHelp pprefs pinfo = do
args <- getArgs
case execParserPure pprefs pinfo args of
Right a -> return a
Left failure -> do
progn <- getProgName
msg <- AT.errMessage failure progn
let extra = if null args
then AH.parserHelpText pprefs pinfo
else ""
let c = errExitCode failure
case c of
ExitSuccess -> putStr (msg ++ extra)
_ -> hPutStr stderr (msg ++ extra)
exitWith c
main :: IO ()
main = execParserWithHelp (prefs idm) opts >>= run
opts :: ParserInfo Command
opts = info (commands <**> helper) idm
run :: Command -> IO ()
run = ...这基本上只是带有一个小块的customExecParser,它检查are是否为空。如果是,它将显示解析器帮助。
发布于 2016-09-12 03:16:15
恢复了一个旧的主题,但是我已经为此添加了showHelpOnEmpty pref,所以现在很简单。给定解析器p :: ParserInfo a
run :: IO a
run = customExecParser (prefs showHelpOnEmpty) p发布于 2015-09-30 01:41:00
如果您只想打印所有错误的--help输出,包括当程序运行时没有参数,那么将对execParser的调用替换为对showHelpOnErrorExecParser的调用,
-- | A version of 'execParser' which shows full help on error.
--
-- The regular 'execParser' only prints usage on error, which doesn't
-- include the options, subcommands, or mention of the help switch
-- @--help@.
showHelpOnErrorExecParser :: ParserInfo a -> IO a
showHelpOnErrorExecParser = customExecParser (prefs showHelpOnError)基于评论的问题链接在接受的答案中。
https://stackoverflow.com/questions/20173409
复制相似问题