What is the design pattern for processing command

2020-02-07 19:45发布

If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and calling the appropriate handler functions?

Consider:

myprogram -f filename -d directory -r regex

How do you organize the handler functions after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer)

16条回答
你好瞎i
2楼-- · 2020-02-07 20:00

You didn't mention the language, but for Java we've loved Apache Commons CLI. For C/C++, getopt.

查看更多
手持菜刀,她持情操
3楼-- · 2020-02-07 20:00

A few comments on this...

First, while there aren't any patterns per se, writing a parser is essentially a mechanical exercise, since given a grammar, a parser can be easily generated. Tools like Bison, and ANTLR come to mind.

That said, parser generators are usually overkill for the command line. So the usual pattern is to write one yourself (as others have demonstrated) a few times until you get sick of dealing with the tedious detail and find a library to do it for you.

I wrote one for C++ that saves a bunch of effort that getopt imparts and makes nice use of templates: TCLAP

查看更多
看我几分像从前
4楼-- · 2020-02-07 20:00

You don't mention a language for this but if you are looking for a really nice Objective-C wrapper around getopt then Dave Dribin's DDCLI framework is really nice.

http://www.dribin.org/dave/blog/archives/2008/04/29/ddcli

查看更多
\"骚年 ilove
5楼-- · 2020-02-07 20:01

The boost::program_options library is nice if you're in C++ and have the luxury of using Boost.

查看更多
我命由我不由天
6楼-- · 2020-02-07 20:01

I'm riffing on the ANTLR answer by mes5k. This link to Codeproject is for an article that discusses ANLTR and using the visit pattern to implement the actions you want you app to take. It's well written and worth reviewing.

查看更多
甜甜的少女心
7楼-- · 2020-02-07 20:03

I am not as much interested in the libraries, though that is definitely helpful. I was looking more for some "pseudo code" that illustrates the processing of say your average bunch of flags and a bunch of longer arguments, as an example.

查看更多
登录 后发表回答