argument_parsing.pai

< Prev | Back | Next >


# Demonstrate how to parse arguments from the command line
# You can run this script with the following command:
#   paisley examples/argument_parsing.pai -- --arg1 value1 -2 123 positional1 positional2 --arg3=true

require arg

# The list of arguments, and whether they're positional, require a value, or whatever else.
let config = {
    'arg1' => {
        'type' => 'string',
        'default' => 'default value',
        'short' => '1',
        'description' => 'The first flag',
    },
    'arg2' => {
        'type' => 'number',
        'default' => 10,
        'short' => '2',
        'description' => 'The second flag',
    },
    'arg3' => {
        'type' => 'boolean',
        'required' => true, # flag is required, so no default value needed
        'short' => '3',
        'description' => 'The third flag',
    },
    '-' => (
        ('pos1', true, 'The first positional argument'), # Positional argument, required
        ('pos2', false, 'The second positional argument'), # Positional argument, optional
    ),
}

# The info to use when the `--help` flag is given.
let info = {
    'name' => 'test',
    'description' => 'An example program that parses arguments',
}

# Parse the arguments
# Note that if the user passes '--help' or '-h', the program will automatically exit. This cannot be caught.
# If the arguments are invalid, an exception will be raised, which can be caught and handled.
let args = {\arg.parse(@, config, info)}

# Alternative way of doing the same thing, but more verbose:
# let args = ${call arg.parse {@} {config} {info} }

# Print the parsed arguments
print {args.json_encode(true)}

< Prev | Back | Next >