A CLI in both
Ruby with OptionParser
The tool greets a name a number of times. Both versions take the same two flags, give the same defaults, and print one line per greeting.
require "optparse" options = { count: 1, name: "guest" } OptionParser.new do |parser| parser.on("-c", "--count N", Integer, "How many greetings") { |value| options[:count] = value } parser.on("-n", "--name NAME", "Who to greet") { |value| options[:name] = value } end.parse! options[:count].times { puts "Hello, #{options[:name]}" }
Python with argparse
import argparse parser = argparse.ArgumentParser() parser.add_argument("-c", "--count", type=int, default=1) parser.add_argument("-n", "--name", default="guest") args = parser.parse_args() for _ in range(args.count): print(f"Hello, {args.name}")
The same run in both
ruby greet.rb -c 3 -n Ada
Hello, Ada
Hello, Ada
Hello, Ada
python3 greet.py -c 3 -n Ada
Hello, Ada
Hello, Ada
Hello, Ada
Without flags both fall back to one greeting for a guest:
ruby greet.rb
Hello, guest
python3 greet.py
Hello, guest
An unknown flag shows the second difference, the exit code:
ruby greet.rb --bad
greet.rb:7:in '<main>': invalid option: --bad (OptionParser::InvalidOption)
python3 greet.py --bad
usage: greet.py [-h] [-c COUNT] [-n NAME]
greet.py: error: unrecognized arguments: --bad
Ruby exits 1 with a Ruby exception on stderr; Python exits 2 with a usage line and its own error message. A pipeline sees both as failures, but the 2 against 1 matters when a script branches on the status.
What differs
- The declaration. Both describe a flag once with a short and a long form. OptionParser takes the type as a positional argument (Integer); argparse takes it as a keyword (type=int).
- Where the values land. OptionParser calls back into a hash the program already owns. argparse builds an object with one attribute per flag, so args.count appears without a declaration.
- Help. Both print usage and flag descriptions for -h/--help; the text and the layout differ, and neither is a contract a script should parse.
- Exit codes. A bad flag is a Ruby exception (1) and a Python argument error (2), as above.
For a larger tool both languages have subcommand libraries (Ruby has optparse plus a dispatch hash, Python has argparse subparsers). The shape of the code is the same either way: parse once, validate, then call one method.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How do the two libraries declare the type of a flag value?
Answer
OptionParser takes it as a positional argument, argparse as the type keyword
OptionParser writes Integer in the middle of the call, and argparse writes type=int after the flag names.
-
What does this program print?
require "optparse" options = { count: 1 } OptionParser.new { |p| p.on("-c", "--count N", Integer) { |v| options[:count] = v } }.parse!(["-c", "3"]) puts options[:count]Answer
3
The block stores the parsed number in the hash the program owns, and the default is replaced.
-
What does this program print?
3.times { puts "Hello, Ada" }Answer
Hello, Ada / Hello, Ada / Hello, Ada
times runs the block once per count, which is the loop both versions use for the greeting.
-
What does this program print?
options = { count: 1, name: "guest" } puts "Hello, #{options[:name]}"Answer
Hello, guest
The default name is the value the CLI falls back to when the flag is absent, which is the same default argparse writes.
-
What does this program print?
require "optparse" begin OptionParser.new { |p| p.on("-c N", Integer) { } }.parse!(["--bad"]) rescue OptionParser::InvalidOption => e puts e.class endAnswer
OptionParser::InvalidOption
An unknown flag is an InvalidOption, which is the Ruby exception the command prints before exiting one.
-
A bad flag exits with which status in each language?
Answer
Ruby exits 1 and Python exits 2
The difference matters to a script that branches on the status, and a pipeline only needs both to be nonzero.
-
What does this program print?
require "optparse" options = {} OptionParser.new { |p| p.on("-n", "--name NAME") { |v| options[:name] = v } }.parse!(["-n", "Ada"]) p optionsAnswer
{:name => "Ada"}
The callback stores the value under the symbol the program chose, and parse! removes the flag and its value from the arguments.
-
What does this program print?
require "optparse" argv = ["-c", "3", "extra"] OptionParser.new { |p| p.on("-c N", Integer) { } }.parse!(argv) p argvAnswer
["extra"]
parse! consumes the flags it knows and leaves the positional arguments, which is where a subcommand would be read.
-
Where do the parsed values land in each library?
Answer
In a hash the Ruby program owns, and in an object with one attribute per flag in Python
The callback shape and the namespace shape are the two designs, and the rest of the program reads one or the other.
-
What does this program print?
require "optparse" options = { count: 1 } OptionParser.new { |p| p.on("-c", "--count N", Integer) { |v| options[:count] = v } }.parse!([]) puts options[:count]Answer
1
With no flag on the command line the default the program wrote stays in place, the same way argparse keeps its default.
Article author: Arthur Isaev